-
1
module BxBlockLogin
-
1
class AccountAdapter
-
1
include Wisper::Publisher
-
-
1
def login_account(account_params)
-
# case account_params.type
-
# when 'sms_account'
-
# phone = Phonelib.parse(account_params.full_phone_number).sanitized
-
# account = AccountBlock::SmsAccount.find_by(
-
# full_phone_number: phone,
-
# activated: true)
-
# when 'email_account'
-
# email = account_params.email.downcase
-
-
# account = AccountBlock::EmailAccount
-
# .where('LOWER(email) = ?', email)
-
# .where(:activated => true)
-
# .first
-
# when 'social_account'
-
# account = AccountBlock::SocialAccount.find_by(
-
# email: account_params.email.downcase,
-
# unique_auth_id: account_params.unique_auth_id,
-
# activated: true)
-
# end
-
5
if ["Publisher", "School Admin", "Teacher"].include?(account_params.type)
-
1
account = AccountBlock::Account .where("lower(email) = ?", account_params.email.downcase) .joins(:role) .where(roles: { name: account_params.type }) .where(activated: true) .last
-
1
if !account.present?
-
1
broadcast(:Account_does_not_exits)
-
1
return
-
end
-
end
-
-
4
if account_params.type == "Student"
-
4
account = AccountBlock::Account.where(student_unique_id: account_params.unique_id).where(activated: true).last
-
4
if !account.present?
-
1
broadcast(:Please_enter_valid_student_id_or_account_not_activated)
-
1
return
-
end
-
-
end
-
-
3
wrong_pin = false
-
-
3
if account.pin != account_params.pin
-
2
wrong_pin = true
-
end
-
-
3
if wrong_pin && account.one_time_pin == account_params.pin && account.is_reset
-
1
wrong_pin = false
-
end
-
-
3
if wrong_pin
-
1
broadcast(:Please_enter_valid_pin)
-
1
return
-
end
-
-
2
unless account.present?
-
broadcast(:account_not_found)
-
return
-
end
-
-
2
if account.present?
-
2
token, refresh_token = generate_tokens(account.id)
-
2
broadcast(:successful_login, account, token, refresh_token)
-
end
-
end
-
-
1
def generate_tokens(account_id)
-
[
-
2
BuilderJsonWebToken.encode(account_id, 1.day.from_now, token_type: 'login'),
-
BuilderJsonWebToken.encode(account_id, 1.year.from_now, token_type: 'refresh')
-
]
-
end
-
end
-
end
-
1
ActiveAdmin.register BxBlockContentManagement::AboutUs, as: "About Us" do
-
1
menu parent: ["Content Management"]
-
1
actions :all
-
1
permit_params :title, :description, :email, :phone_number
-
-
1
index do
-
1
selectable_column
-
1
id_column
-
1
column :email
-
1
column :phone_number
-
1
column :title do |setting|
-
1
raw(setting.title)
-
end
-
1
column :description do |setting|
-
1
raw(setting.description)
-
end
-
1
actions
-
end
-
-
1
form do |f|
-
1
f.semantic_errors
-
1
f.inputs do
-
1
f.input :email
-
1
f.input :phone_number
-
1
f.input :title
-
1
f.input :description
-
end
-
1
f.actions
-
end
-
-
1
show do |d|
-
1
attributes_table do
-
1
row :email
-
1
row :phone_number
-
1
row :title do |setting|
-
#raw(setting.title)
-
1
setting.title
-
end
-
1
row :description do |setting|
-
1
raw(setting.description)
-
end
-
end
-
end
-
end
-
1
module AccountGroups
-
1
class Load
-
1
@@loaded_from_gem = false
-
1
def self.is_loaded_from_gem
-
1
@@loaded_from_gem
-
end
-
-
1
def self.loaded
-
end
-
-
# Check if this file is loaded from gem directory or not
-
# The gem directory looks like
-
# /template-app/.gems/gems/bx_block_custom_user_subs-0.0.7/app/admin/subscription.rb
-
# if it has block's name in it then it's a gem
-
1
@@loaded_from_gem = Load.method(:loaded).source_location.first.include?("bx_block_")
-
end
-
end
-
-
1
unless AccountGroups::Load.is_loaded_from_gem
-
1
ActiveAdmin.register BxBlockAccountGroups::Group do
-
1
permit_params :name, :settings, :account_ids
-
-
1
index do
-
selectable_column
-
id_column
-
column :name
-
column :settings
-
column :account_ids
-
actions
-
end
-
-
1
filter :name
-
1
filter :created_at
-
-
1
form do |f|
-
f.inputs do
-
f.input :name
-
f.input :settings
-
f.input :account_ids
-
end
-
f.actions
-
end
-
end
-
end
-
1
module AdminUsers
-
1
class Load
-
1
@@loaded_from_gem = false
-
1
def self.is_loaded_from_gem
-
1
@@loaded_from_gem
-
end
-
-
1
def self.loaded
-
end
-
-
# Check if this file is loaded from gem directory or not
-
# The gem directory looks like
-
# /template-app/.gems/gems/bx_block_custom_user_subs-0.0.7/app/admin/subscription.rb
-
# if it has block's name in it then it's a gem
-
1
@@loaded_from_gem = Load.method('loaded').source_location.first.include?('bx_block_')
-
end
-
end
-
-
1
unless AdminUsers::Load.is_loaded_from_gem
-
1
ActiveAdmin.register AdminUser do
-
1
permit_params :email, :role, :school_id, :password, :password_confirmation
-
-
1
index do
-
1
selectable_column
-
1
id_column
-
1
column :email
-
1
column :current_sign_in_at
-
1
column :sign_in_count
-
1
column :created_at
-
1
actions
-
end
-
-
1
show do
-
1
attributes_table do
-
1
row :email
-
1
row :role
-
1
row :created_at
-
1
row :updated_at
-
end
-
end
-
-
1
filter :email
-
1
filter :current_sign_in_at
-
1
filter :sign_in_count
-
1
filter :created_at
-
-
1
before_build do |admin_user|
-
1
admin_user.role ||= :super_admin
-
end
-
-
1
form do |f|
-
1
f.inputs do
-
1
f.input :email
-
1
f.input :password
-
1
f.input :password_confirmation
-
end
-
1
f.actions
-
end
-
1
controller do
-
1
def scoped_collection
-
3
AdminUser.where(role: :super_admin)
-
end
-
end
-
end
-
end
-
1
ActiveAdmin.register BxBlockCatalogue::Assignment, as: "Assignment" do
-
1
menu false
-
1
permit_params :id, :title, :subject_id, :description, :subject_management_id, :assignment, :school_class_id, :school_id, :class_division_id, :account_id
-
-
1
action_item :back, only: [:new, :show, :edit] do
-
3
subject_id = resource&.subject_management_id || params[:subject_management_id]
-
3
link_to 'Back ', admin_subject_and_teacher_path(subject_id), class: 'button'
-
end
-
-
1
controller do
-
1
def destroy
-
1
subject = resource&.subject_management_id
-
1
resource.destroy
-
1
redirect_to admin_subject_and_teacher_path(subject), notice: 'This assignment is delete successfully.'
-
end
-
-
1
def create
-
3
create! do |format|
-
3
if resource.valid?
-
1
redirect_to admin_subject_and_teacher_path(resource&.subject_management_id), notice: "Assignment created successfully." and return
-
else
-
2
handle_assignment_errors
-
2
redirect_to new_admin_assignment_path(
-
subject_id: params[:assignment][:subject_id],
-
subject_management_id: params[:assignment][:subject_management_id],
-
class_division_id: params[:assignment][:class_division_id],
-
account_id: params[:assignment][:account_id],
-
format: :html
-
) and return
-
end
-
end
-
end
-
-
1
def update
-
1
update! do |format|
-
1
if resource.valid?
-
if params[:assignment][:assignment].blank?
-
resource.errors.add(:assignment, "can't be blank")
-
render :edit, location: edit_admin_assignment_path(subject_id: params[:assignment][:subject_id], subject_management_id: params[:assignment][:subject_management_id], class_division_id: params[:assignment][:class_division_id], account_id: params[:assignment][:account_id])
-
return
-
end
-
redirect_to admin_subject_and_teacher_path(resource&.subject_management_id), notice: "Assignment updated successfully." and return
-
else
-
1
render :edit, location: edit_admin_assignment_path(subject_id: params[:assignment][:subject_id], subject_management_id: params[:assignment][:subject_management_id], class_division_id: params[:assignment][:class_division_id], account_id: params[:assignment][:account_id])
-
1
return
-
end
-
end
-
end
-
-
1
private
-
-
1
def handle_assignment_errors
-
2
if resource.errors.include?(:assignment)
-
2
flash[:error] = resource.errors[:assignment].join(', ')
-
else
-
flash[:error] = 'Please enter data in mandatory fields'
-
end
-
end
-
end
-
-
1
index do
-
1
selectable_column
-
1
id_column
-
1
column :title
-
1
column :subject_id do |assign|
-
1
BxBlockCatalogue::Subject.find(assign.subject_id).subject_name rescue nil
-
end
-
1
column :description
-
1
column :assignment do |assign|
-
1
if assign.assignment.attached?
-
1
link_to("View", rails_blob_path(assign.assignment, disposition: "attachment"))
-
else
-
"No PDF attached"
-
end
-
end
-
1
actions
-
end
-
-
1
form do |f|
-
3
f.semantic_errors(*f.object.errors.keys)
-
3
f.inputs do
-
3
f.input :title
-
3
subject = if f.object.new_record?
-
1
BxBlockCatalogue::Subject.where(id: params[:subject_id].to_i)
-
else
-
2
BxBlockCatalogue::Subject.where(id: f.object.subject_id)
-
end
-
3
f.input :subject_id, as: :select, collection: subject.pluck(:subject_name, :id), include_blank: false
-
3
f.input :description
-
-
3
f.input :assignment, label: 'Add Assignment ', as: :file, input_html: { direct_upload: true }
-
-
3
if f.object.new_record?
-
1
f.input :subject_management_id, as: :hidden, input_html: { value: params[:subject_management_id] }
-
1
f.input :class_division_id, as: :hidden, input_html: { value: params[:class_division_id] }
-
1
f.input :school_class_id, as: :hidden, input_html: { value: params[:school_class_id] }
-
1
f.input :school_id, as: :hidden, input_html: { value: params[:school_id] }
-
1
f.input :account_id, as: :hidden, input_html: { value: params[:account_id] }
-
else
-
2
f.input :subject_management_id, as: :hidden, input_html: { value: f.object.subject_management_id }
-
2
f.input :class_division_id, as: :hidden, input_html: { value: f.object.class_division_id }
-
2
f.input :school_class_id, as: :hidden, input_html: { value: f.object.school_class_id }
-
2
f.input :school_id, as: :hidden, input_html: { value: f.object.school_id }
-
2
f.input :account_id, as: :hidden, input_html: { value: f.object.account_id }
-
end
-
end
-
3
f.actions do
-
3
if resource.persisted?
-
2
f.action :submit, as: :button, label: 'Update Assignment'
-
2
f.action :cancel
-
else
-
1
f.action :submit, label: "Create Assignment"
-
1
f.action :cancel
-
end
-
end
-
end
-
-
1
show do
-
1
attributes_table do
-
1
row :id
-
1
row :title
-
1
row :subject_id do |assign|
-
1
BxBlockCatalogue::Subject.find(assign.subject_id).subject_name rescue nil
-
end
-
1
row :description
-
1
row :assignment do |assign|
-
1
if assign.assignment.attached?
-
1
link_to("View ", rails_blob_path(assign.assignment, disposition: "attachment"))
-
else
-
"No PDF attached"
-
end
-
end
-
end
-
end
-
-
end
-
-
1
module BxBlockInvoice
-
end
-
-
1
ActiveAdmin.register BxBlockInvoice::Invoice, as: "Invoice" do
-
1
menu parent: ["Building block invoice"]
-
-
1
actions :all, except: [:new, :edit]
-
-
1
permit_params :invoice_number, :invoice_date, :bill_to_customer_name, :bill_to_customer_address, :bill_to_customer_city, :bill_to_customer_zip_code, :bill_to_customer_phone_number, :bill_to_customer_email, invoice_items_attributes: [:id, :item_id, :invoice_id, :_destroy]
-
-
1
index do
-
selectable_column
-
id_column
-
column :order_id
-
column :invoice_number
-
column :total_amount
-
column :company_zip_code
-
column :company_phone_number
-
column :bill_to_name
-
column :bill_to_company_name
-
column :bill_to_zip_code
-
-
actions do |obj|
-
host = Rails.env.production? ? ENV["BASE_URL"] : "http://localhost:3000"
-
if obj.invoice_pdf.attached?
-
item "Download", "#{host}/#{Rails.application.routes.url_helpers.rails_blob_path(obj.invoice_pdf,
-
only_path: true)}"
-
end
-
end
-
end
-
-
1
show do |cs|
-
attributes_table do
-
row :order_id
-
row :invoice_number
-
row :invoice_date
-
row :total_amount
-
row :company_address
-
row :company_city
-
row :company_zip_code
-
row :company_phone_number
-
row :bill_to_name
-
row :bill_to_company_name
-
row :bill_to_address
-
row :bill_to_city
-
row :bill_to_zip_code
-
row :bill_to_phone_number
-
row :bill_to_email
-
row :item_name
-
row :item_unit_price
-
end
-
-
panel "Invoice Items" do
-
attributes_table_for invoice.invoice_items do
-
rows :id
-
rows :item_id
-
rows :invoice_id
-
end
-
end
-
end
-
-
1
form do |f|
-
f.inputs do
-
f.inputs "Invoice Items" do
-
f.has_many :invoice_items, heading: false, allow_destroy: true do |cd|
-
cd.input :id
-
cd.input :item_id
-
cd.input :invoice_id
-
end
-
end
-
end
-
actions
-
end
-
end
-
1
module BxBlockInvoiceCompany
-
end
-
-
1
ActiveAdmin.register BxBlockInvoice::Company, as: "Company" do
-
1
menu parent: ["Building block invoice"]
-
-
1
permit_params :name, :address, :city, :zip_code, :phone_number, :email
-
-
1
index do
-
selectable_column
-
id_column
-
column :name
-
column :address
-
column :city
-
column :zip_code
-
column :phone_number
-
column :email
-
actions
-
end
-
-
1
show do
-
attributes_table do
-
row :name
-
row :address
-
row :city
-
row :zip_code
-
row :phone_number
-
row :email
-
end
-
end
-
-
1
form do |f|
-
f.semantic_errors(*f.object.errors.keys)
-
f.inputs do
-
f.inputs :name
-
f.inputs :address
-
f.inputs :city
-
f.inputs :zip_code
-
f.inputs :phone_number
-
f.inputs :email
-
end
-
f.actions
-
end
-
end
-
1
module BxBlockInvoiceOrder
-
end
-
-
1
ActiveAdmin.register BxBlockInvoice::Order, as: "Order_invoice" do
-
1
menu parent: ["Building block invoice"]
-
-
1
permit_params :order_number, :order_date, :customer_name, :customer_address, :customer_phone_number, :email, :company_id, items_attributes: [:id, :_destroy, :order_id, :item_name, :item_unit_price], bill_to_addresses_attributes: [:name, :company_name, :address, :city, :zip_code, :phone_number, :email, :order_id]
-
-
1
form do |f|
-
f.inputs do
-
f.input :company_id, as: :select, include_blank: false, collection: BxBlockInvoice::Company.all
-
f.input :order_date
-
f.input :customer_name
-
f.input :customer_address
-
f.input :customer_phone_number
-
f.input :email
-
f.has_many :items do |item|
-
item.input :item_name
-
item.input :item_unit_price
-
end
-
f.has_many :bill_to_addresses do |bill|
-
bill.input :name
-
bill.input :company_name
-
bill.input :address
-
bill.input :city
-
bill.input :zip_code
-
bill.input :phone_number
-
bill.input :email
-
end
-
end
-
f.actions
-
end
-
-
1
show do
-
attributes_table do
-
row :id
-
row :order_number
-
row :order_date
-
row :customer_name
-
row :customer_address
-
row :customer_phone_number
-
row :email
-
row :total_amount
-
row :company do |object|
-
link_to object.company.name, admin_company_path(object.company.id)
-
end
-
panel "Items" do
-
table_for resource.items do
-
column "Item ID", &:id
-
column :item_unit_price
-
end
-
end
-
panel "Bill to Address" do
-
table_for resource.bill_to_addresses do
-
column :name
-
column :company_name
-
column :address
-
column :city
-
column :zip_code
-
column :phone_number
-
column :email
-
end
-
end
-
end
-
end
-
end
-
1
module BxBlockMultipageforms2UserProfiles; end
-
-
1
ActiveAdmin.register BxBlockMultipageforms2::UserProfile, as: "UserProfile" do
-
-
# See permitted parameters documentation:
-
# https://github.com/activeadmin/activeadmin/blob/master/docs/2-resource-customization.md#setting-up-strong-parameters
-
#
-
# Uncomment all parameters which should be permitted for assignment
-
#
-
1
permit_params :first_name, :last_name, :phone_number, :email, :gender, :country, :industry, :message
-
#
-
# or
-
#
-
1
actions :all, :except => [:new, :edit, :destroy]
-
# permit_params do
-
# permitted = [:first_name, :last_name, :phone_number, :email, :gender, :country, :industry, :message]
-
# permitted << :other if params[:action] == 'create' && current_user.admin?
-
# permitted
-
# end
-
-
end
-
1
ActiveAdmin.register BxBlockCategories::ClassDivision, as: "ClassDivision" do
-
1
menu false
-
-
1
permit_params :id, :division_name, :school_id, :school_class_id, :account_id, subject_ids: [], subject_teacher_ids: []
-
-
1
action_item :back, only: :show do
-
2
link_to 'Back to Class', admin_class_path(resource.school_class_id), class: 'button'
-
end
-
-
1
after_create do |class_division|
-
class_division.account.update(class_division_id: class_division.id)
-
end
-
-
1
controller do
-
1
def destroy
-
1
school_class_id = resource.school_class_id
-
1
AccountBlock::Account.where(role_id: BxBlockRolesPermissions::Role.find_by(name: 'Student').id,class_division_id: resource.id).delete_all
-
1
resource.subject_teacher_ids.each do |account|
-
account = AccountBlock::Account.find_by(id: account)
-
account.subject_teacher_division_ids = account.subject_teacher_division_ids - [resource.id]
-
# account.subject_teacher_class_ids = account.subject_teacher_class_ids - [resource.school_class.id]
-
account.save
-
end
-
1
AccountBlock::Account.where(role_id: BxBlockRolesPermissions::Role.find_by(name: 'Teacher').id,class_division_id: resource.id).update(class_division_id: nil, school_class_id: nil)
-
1
resource.destroy
-
1
redirect_to admin_class_path(school_class_id), notice: "Class Division deleted successfully."
-
end
-
-
1
def update
-
1
subject_ids = resource.subject_ids || []
-
1
subject_ids += [params[:class_division][:subject_ids]]
-
1
subject_teacher_ids = resource.subject_teacher_ids || []
-
1
subject_teacher_ids += [params[:class_division][:subject_teacher_ids]]
-
1
subject_ids = subject_ids.uniq
-
1
subject_teacher_ids = subject_teacher_ids.uniq
-
1
resource.update(subject_ids: subject_ids, subject_teacher_ids: subject_teacher_ids)
-
1
subject_management = resource.subject_managements.find_or_create_by!(subject_id: params[:class_division][:subject_ids], account_id: params[:class_division][:subject_teacher_ids])
-
1
account = AccountBlock::Account.find_by(id: subject_management.account_id)
-
1
account_subject_id = account.subject_ids || []
-
1
account_subject_id += [params[:class_division][:subject_ids]]
-
1
subject_management_ids = account.subject_management_ids || []
-
1
subject_management_ids += [subject_management.id]
-
1
subject_teacher_division_ids = account.subject_teacher_division_ids || []
-
1
subject_teacher_division_ids += [subject_management.class_division_id]
-
1
school_class = subject_management.class_division.school_class_id
-
1
subject_teacher_class_ids = account.subject_teacher_class_ids || []
-
1
subject_teacher_class_ids += [school_class]
-
1
account.update(subject_ids: account_subject_id.uniq, subject_management_ids: subject_management_ids.uniq, subject_teacher_division_ids: subject_teacher_division_ids.uniq, subject_teacher_class_ids: subject_teacher_class_ids.uniq)
-
1
redirect_to admin_class_division_path(resource), notice: 'Subject and teacher updated successfully.'
-
end
-
end
-
-
1
index do
-
1
id_column
-
1
column :division_name
-
1
actions
-
end
-
-
1
show title: "Class Division" do |cs|
-
2
attributes_table do
-
2
row "Class" do
-
2
"#{cs.school_class.class_number} #{cs.division_name}"
-
end
-
-
2
row 'Add Subject and Teacher' do
-
2
form_for(resource, url: admin_class_division_path(resource), method: :patch, html: { multipart: true }) do |f|
-
2
panel 'Subject' do
-
2
selected_subject_ids = resource.subject_ids || []
-
2
available_subjects = BxBlockCatalogue::Subject.where.not(id: selected_subject_ids)
-
2
f.select :subject_ids, options_for_select(available_subjects.pluck(:subject_name, :id), selected: selected_subject_ids)
-
end
-
-
2
panel 'Subject Teacher' do
-
# selected_teacher_ids = resource.subject_teacher_ids || []
-
2
available_teachers = AccountBlock::Account.where(role_id: BxBlockRolesPermissions::Role.find_by(name: "Teacher")).where(school_id: resource&.school_id)#.where.not(id: selected_teacher_ids)
-
2
f.select :subject_teacher_ids, options_for_select(available_teachers.pluck(:email, :id),)
-
end
-
-
2
f.submit 'Update'
-
end
-
end
-
2
subject_and_teacher = resource&.subject_managements
-
2
render "/admin/subject_and_teacher/index", locals: { subject_and_teacher: subject_and_teacher }, layout: "active_admin"
-
-
-
2
panel "Students in class #{class_division.school_class.class_number} #{class_division.division_name}" do
-
2
panel link_to 'Add New Student', new_admin_student_url(class_division_id: class_division.id, school_class_id: class_division.school_class_id, school_id: class_division.school_id) do
-
end
-
2
students = AccountBlock::Account.joins(:role).where(roles: { name: "Student" }).where(class_division_id: class_division.id)
-
2
render "/admin/student/index", locals: { students: students }, layout: "active_admin"
-
end
-
end
-
end
-
-
1
form do |f|
-
2
f.inputs do
-
2
f.input :division_name
-
2
class_collection = if f.object.new_record?
-
1
BxBlockCategories::SchoolClass.where(id: params[:school_class_id].to_i)
-
else
-
1
BxBlockCategories::SchoolClass.where(id: f.object.school_class_id)
-
end
-
2
f.input :school_class_id, as: :select, collection: class_collection.pluck(:class_number, :id), include_blank: false
-
2
account_collection = if f.object.persisted?
-
1
AccountBlock::Account.where(role_id: BxBlockRolesPermissions::Role.find_by(name: "Teacher"), class_division_id: f.object.id).pluck(:email, :id)
-
else
-
1
AccountBlock::Account.where(role_id: BxBlockRolesPermissions::Role.find_by(name: "Teacher"), school_id: params[:school_id], school_class_id: params[:id], class_division_id: nil).pluck(:email, :id)
-
end
-
2
f.input :account_id, label: "Class Teacher", as: :select, collection: account_collection, include_blank: false
-
end
-
2
f.actions do
-
2
if resource.persisted?
-
1
f.action :submit, as: :button, label: 'Update Class Division'
-
1
f.action :cancel#, as: :button, label: 'Cancel' ,wrapper_html: { onclick: "window.location.href = '#{admin_class_division_path(params[:id])}'" }
-
else
-
1
f.actions
-
end
-
end
-
end
-
end
-
-
1
module Dashboard
-
1
class Load
-
1
@@loaded_from_gem = false
-
1
def self.is_loaded_from_gem
-
1
@@loaded_from_gem
-
end
-
-
1
def self.loaded
-
end
-
-
1
@@loaded_from_gem = Load.method('loaded').source_location.first.include?('bx_block_')
-
end
-
end
-
-
# unless Dashboard::Load.is_loaded_from_gem
-
# ActiveAdmin.register_page "Dashboard" do
-
# menu priority: 1, label: proc { I18n.t("active_admin.dashboard") }
-
-
# content title: proc { I18n.t("active_admin.dashboard") } do
-
# columns do
-
# column do
-
# panel "Total Students" do
-
# ul do
-
# link_to AccountBlock::Account.joins(:role).where(roles: {name: "Student"}).size, admin_students_url()
-
# end
-
# end
-
-
# panel "Total School Admins" do
-
# ul do
-
# link_to AccountBlock::Account.joins(:role).where(roles: {name: "School Admin"}).size, admin_school_admins_url()
-
# end
-
# end
-
# end
-
-
# column do
-
# panel "Total Teachers" do
-
# ul do
-
# link_to AccountBlock::Account.joins(:role).where(roles: {name: "Teacher"}).size, admin_teachers_url()
-
# end
-
# end
-
-
# panel "Total Publishers" do
-
# ul do
-
# link_to AccountBlock::Account.joins(:role).where(roles: {name: "Publisher"}).size, admin_publishers_url()
-
# end
-
# end
-
# end
-
# column do
-
# panel "Total Ebooks" do
-
# ul do
-
# li do
-
# link_to "#{BxBlockBulkUploading::Ebook.all.size}", admin_ebooks_path
-
# end
-
# end
-
# end
-
-
# panel "Total Ebook Bundles" do
-
# ul do
-
# li do
-
# link_to "#{BxBlockBulkUploading::BundleManagement.all.size}", admin_bundle_managements_path
-
# end
-
# end
-
# end
-
# end
-
# end
-
# end
-
# end
-
# end
-
1
unless Dashboard::Load.is_loaded_from_gem
-
1
ActiveAdmin.register_page "Dashboard" do
-
86
menu priority: 1, label: proc { I18n.t("active_admin.dashboard") }
-
-
19
content title: proc { I18n.t("active_admin.dashboard") } do
-
9
if current_admin_user.super_admin?
-
6
columns do
-
6
column do
-
6
panel "Total Students" do
-
6
ul do
-
6
link_to AccountBlock::Account.joins(:role).where(roles: {name: "Student"}).size, admin_students_url()
-
end
-
end
-
-
6
panel "Total School Admins" do
-
6
ul do
-
6
link_to AccountBlock::Account.joins(:role).where(roles: {name: "School Admin"}).size, admin_school_admins_url()
-
end
-
end
-
end
-
-
6
column do
-
6
panel "Total Teachers" do
-
6
ul do
-
6
link_to AccountBlock::Account.joins(:role).where(roles: {name: "Teacher"}).size, admin_teachers_url()
-
end
-
end
-
-
6
panel "Total Publishers" do
-
6
ul do
-
6
link_to AccountBlock::Account.joins(:role).where(roles: {name: "Publisher"}).size, admin_publishers_url()
-
end
-
end
-
end
-
6
column do
-
6
panel "Total Ebooks" do
-
6
ul do
-
6
li do
-
6
link_to "#{BxBlockBulkUploading::Ebook.all.size}", admin_ebooks_path
-
end
-
end
-
end
-
-
6
panel "Total Ebook Bundles" do
-
6
ul do
-
6
li do
-
6
link_to "#{BxBlockBulkUploading::BundleManagement.all.size}", admin_bundle_managements_path
-
end
-
end
-
end
-
end
-
end
-
else
-
3
school = current_admin_user.school_id
-
3
columns do
-
3
column do
-
3
panel "Total Students" do
-
3
ul do
-
3
link_to AccountBlock::Account.where(school_id: school).joins(:role).where(roles: { name: "Student" }).size, admin_students_url()
-
end
-
end
-
end
-
end
-
-
3
columns do
-
3
column do
-
3
panel "Total Teacher" do
-
3
ul do
-
3
link_to AccountBlock::Account.where(school_id: school).joins(:role).where(roles: { name: "Teacher" }).size, admin_teachers_url()
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
1
require 'pdf/reader'
-
1
require 'open-uri'
-
1
ActiveAdmin.register BxBlockBulkUploading::Ebook, as: "Ebook" do
-
1
menu parent: ["User Library"], priority: 1
-
1
actions :all
-
1
permit_params :title, :author, :size, :pages, :edition, :publisher, :publication_date, :formats_available, :language, :description, :price, :commission_percentage, :board, :school_class_id, :subject, :excel_file, :pdf, images: []
-
-
1
collection_action :download_sample_excel, method: :get
-
1
member_action :download_error_excel, method: :get
-
1
current_year = Time.now.year
-
-
1
filter :school_class_id, as: :select, collection: (1..12).to_a, label: "Class"
-
# filter :board, as: :select, collection: BxBlockCategories::School.distinct.pluck(:board), label: "Board"
-
1
filter :subject
-
-
1
index do
-
1
selectable_column
-
1
id_column
-
1
column :title
-
1
column :author
-
1
column :edition
-
1
column :price
-
1
column :created_at
-
1
actions
-
end
-
-
1
show do
-
1
attributes_table do
-
1
row :title
-
1
row :author
-
1
row :size do |ebook|
-
1
if ebook.pdf.attached?
-
1
pdf_size = ebook.pdf.blob.byte_size
-
1
"PDF Size: #{number_to_human_size(pdf_size)}"
-
else
-
"No PDF available."
-
end
-
end
-
1
row :pages do |ebook|
-
1
if ebook.pdf.attached?
-
begin
-
1
pdf_data = ebook.pdf.download.force_encoding('BINARY')
-
1
pdf_info = PDF::Reader.new(StringIO.new(pdf_data))
-
"Pages: #{pdf_info.pages.count}"
-
rescue PDF::Reader::MalformedPDFError => e
-
1
"Error reading PDF: #{e.message}"
-
end
-
else
-
"No PDF available."
-
end
-
end
-
1
row :edition
-
1
row :publisher
-
# row :publisher do |ebook|
-
# begin
-
# Rails.logger.debug("Ebook Publisher ID: #{ebook.publisher}")
-
# publisher_id = ebook.publisher
-
# if publisher_id.present?
-
# publisher = AccountBlock::Account.find_by(id: publisher_id)
-
# Rails.logger.debug("Found Publisher: #{publisher.publication_house_name}") if publisher
-
# "#{publisher.publication_house_name}" if publisher
-
# else
-
# "Publisher ID not present"
-
# end
-
# rescue ActiveRecord::RecordNotFound
-
# Rails.logger.debug("Publisher not found")
-
# "Publisher not found"
-
# end
-
# end
-
1
row :publication_date
-
1
row :formats_available
-
1
row :language
-
1
row :description
-
1
row :price
-
1
row :commission_percentage
-
1
row :board
-
1
row :school_class_id
-
1
row :subject
-
1
row :pdf do |ebook|
-
1
if ebook.pdf.attached?
-
1
iframe(src: rails_blob_path(ebook.pdf, only_path: true), width: "100%", height: "600px", frameborder: "0")
-
else
-
"No PDF available"
-
end
-
end
-
1
row 'Images' do |ebook|
-
1
if ebook.images.attached?
-
1
ul do
-
1
ebook.images.each do |image|
-
1
li do
-
1
image_tag(rails_blob_path(image, only_path: true), height: '100')
-
end
-
end
-
end
-
else
-
'No images'
-
end
-
end
-
end
-
1
active_admin_comments
-
end
-
-
1
form do |f|
-
3
f.inputs "Ebook Details" do
-
3
f.input :title
-
3
f.input :author
-
3
f.input :edition
-
3
publisher = AccountBlock::Account.joins(:role).where(roles: {name: "Publisher"})
-
3
f.input :publisher, as: :select, collection: publisher.distinct.pluck(:publication_house_name),include_blank: false
-
3
f.input :publication_date, as: :date_select,
-
start_year: current_year,
-
end_year: current_year - 100,
-
order: [:day, :month, :year],
-
include_blank: false
-
3
f.input :formats_available
-
3
f.input :language
-
3
f.input :description
-
3
f.input :price
-
3
f.input :commission_percentage
-
3
f.input :board, as: :select, collection: BxBlockCategories::School.distinct.pluck(:board), include_blank: false
-
3
f.input :school_class_id, as: :select, collection: 1..12, include_blank: false
-
3
f.input :subject, as: :select, collection: BxBlockCatalogue::Subject.distinct.pluck(:subject_name), include_blank: false
-
3
f.input :pdf, as: :file, hint: f.object.pdf.attached? ? link_to('View PDF', url_for(f.object.pdf), target: '_blank') : content_tag(:span, 'No PDF available!'), direct_upload: true
-
3
f.input :images, as: :file, input_html: { multiple: true, direct_upload: true }
-
3
if f.object.images.attached?
-
1
div class: 'image-preview-links' do
-
1
f.object.images.each do |image|
-
1
div class: 'image-preview-link' do
-
1
link_to 'Preview Image', url_for(image), target: '_blank'
-
end
-
end
-
end
-
end
-
# f.input :images, as: :file, input_html: { multiple: true, accept: 'image/*', limit: 3, 'data-max-file-count' => 3 }
-
end
-
3
f.actions
-
end
-
-
1
action_item :only => :index do
-
6
link_to 'Upload Excel', :action => 'upload_excel'
-
end
-
1
action_item :only => :index do
-
6
link_to 'Download Sample', :action => 'download_sample'
-
end
-
-
1
collection_action :upload_excel do
-
1
render 'admin/ebooks/upload_excel'
-
end
-
-
1
collection_action :download_sample do
-
1
send_file Rails.root.join('public/sample', 'sample1.xlsx'),
-
filename: 'sample_ebook_template.xlsx',
-
type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
-
end
-
-
1
collection_action :import_excel, method: :post do
-
-
6
if params[:ebook] && params[:ebook][:excel_file].present?
-
5
excel_file = params[:ebook][:excel_file]
-
5
if excel_file.original_filename.match(/\.(xlsx|xls)\z/)
-
4
file = params[:ebook][:excel_file].tempfile
-
# excel = Roo::Excelx.new(file.path)
-
begin
-
4
excel = Roo::Excelx.new(file.path)
-
rescue StandardError
-
1
flash[:error] = 'Error opening the Excel file. Please ensure it is a valid Excel file.'
-
1
return redirect_to :action => :index
-
end
-
3
success_count = 0
-
3
error_count = 0
-
-
3
if excel&.last_row.to_i < 4
-
1
flash[:error] = 'Excel file is blank or does not contain data.'
-
1
return redirect_to :action => :index
-
end
-
-
2
(4..excel.last_row).each do |row_number|
-
3
title = excel.cell(row_number, 1)
-
3
author = excel.cell(row_number, 2)
-
3
edition = excel.cell(row_number, 3)
-
3
publisher = excel.cell(row_number, 4)
-
3
publication_date = excel.cell(row_number, 5)
-
3
formats_available = excel.cell(row_number, 6)
-
3
language = excel.cell(row_number, 7)
-
3
description = excel.cell(row_number, 8)
-
3
price = excel.cell(row_number, 9)
-
3
commission_percentage = excel.cell(row_number, 10)
-
3
board = excel.cell(row_number, 11)
-
3
school_class_id = excel.cell(row_number, 12)
-
3
subject = excel.cell(row_number, 13)
-
3
pdf_path = excel.cell(row_number, 14)
-
12
images_paths = (15..17).map { |col| excel.cell(row_number, col) }
-
-
3
ebook = BxBlockBulkUploading::Ebook.new(title: title, author: author, edition: edition, publisher: publisher, publication_date: publication_date, formats_available: formats_available, language: language, description: description, price: price, commission_percentage: commission_percentage, board: board, school_class_id: school_class_id, subject: subject)
-
3
if pdf_path.present?# && File.exist?(pdf_path)
-
3
pdf_file = download_file_from_link(pdf_path)
-
3
ebook.pdf.attach(io: pdf_file, filename: 'downloaded_pdf.pdf') if pdf_file
-
end
-
-
3
if images_paths.present?
-
3
images_paths.each do |image_link|
-
9
image_link.strip! if image_link.respond_to?(:strip!)
-
9
image_file = download_file_from_link(image_link)
-
9
ebook.images.attach(io: image_file, filename: 'downloaded_image.jpg') if image_file
-
end
-
end
-
-
3
if ebook.valid?
-
ebook.save
-
success_count += 1
-
flash[:notice] = "#{success_count} ebooks imported successfully."
-
else
-
3
ebook.delete
-
3
error_count += 1
-
3
flash[:alert] = "#{error_count} ebooks failed to import due to failed validation or missing required column."
-
end
-
end
-
else
-
1
flash[:error] = 'Please upload a valid Excel file (.xlsx or .xls).'
-
end
-
else
-
1
flash[:alert] = "No file selected for import."
-
end
-
4
redirect_to :action => :index
-
end
-
-
1
controller do
-
1
def download_file_from_link(link)
-
begin
-
12
if link.match(/drive\.google\.com/)
-
4
file_id = link.match(/(?:drive\.google\.com\/.*[?&]id=|drive\.google\.com\/.*\/d\/|drive\.google\.com\/open\?id=)([^"&?\/\s]{28,})/)[1]
-
4
file_content = open("https://drive.google.com/uc?id=#{file_id}").read
-
else
-
8
file_content = URI.open(link).read
-
end
-
3
Tempfile.new.tap do |tempfile|
-
3
tempfile.binmode
-
3
tempfile.write(file_content)
-
3
tempfile.rewind
-
end
-
9
rescue StandardError => e
-
9
Rails.logger.error("Error downloading file from #{link}: #{e.message}")
-
9
nil
-
end
-
end
-
end
-
end
-
1
ActiveAdmin.register BxBlockBulkUploading::BundleManagement, as: "Bundle Management" do
-
1
menu parent: ["User Library"], priority: 2
-
-
1
permit_params :title, :description, :total_pricing, :board, :school_class_id, :subject, :books_count, cover_images: [], ebook_ids: []
-
-
1
index do
-
1
selectable_column
-
1
id_column
-
1
column :title
-
1
column :description
-
1
column :total_pricing do |bundle|
-
1
bundle.calculate_revised_price
-
end
-
1
column :books_count do |bundle|
-
1
bundle.ebooks.count
-
end
-
1
actions
-
end
-
-
1
form do |f|
-
1
f.semantic_errors
-
1
f.inputs "Bundle Details" do
-
1
f.input :title
-
1
f.input :description
-
1
f.input :cover_images, as: :file, input_html: { multiple: true }
-
1
f.input :total_pricing, label: 'Revised Total Pricing', input_html: { readonly: true, value: f.object.calculate_revised_price }
-
1
f.input :board, as: :select, collection: BxBlockCategories::School.distinct.pluck(:board), include_blank: true
-
1
f.input :school_class_id, as: :select, collection: 1..12, include_blank: true
-
1
f.input :subject
-
1
f.inputs "Ebooks" do
-
# f.input :ebook_ids, as: :searchable_select, collection: BxBlockBulkUploading::Ebook.all.pluck(:title, :id), include_blank: false, input_html: { multiple: true }
-
1
f.input :ebook_ids, as: :searchable_select, label: 'Ebooks',
-
collection: BxBlockBulkUploading::Ebook.all.pluck(:title, :id), include_blank: true,
-
input_html: { multiple: true,
-
style: 'width: 200px; font-size: 16px; height: 150px;' }
-
end
-
end
-
1
f.actions
-
end
-
-
1
show do
-
1
attributes_table do
-
1
row 'Cover Images' do |ebook|
-
1
if ebook.cover_images.attached?
-
1
ul do
-
1
ebook.cover_images.each do |image|
-
1
li do
-
1
image_tag(rails_blob_path(image, only_path: true), height: '100')
-
end
-
end
-
end
-
else
-
'No images'
-
end
-
end
-
1
row :title
-
1
row :description
-
1
row :board
-
1
row :school_class_id
-
1
row :books_count do |bundle|
-
1
bundle.ebooks.count
-
end
-
1
row :total_pricing do |bundle|
-
1
bundle.calculate_revised_price
-
end
-
1
row :ebooks do |bundle|
-
1
ul do
-
1
bundle.ebooks.each do |ebook|
-
1
li do
-
1
link_to ebook.title, admin_ebook_path(ebook)
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
1
ActiveAdmin.register BxBlockContentManagement::FaqQuestion, as: "FAQ" do
-
1
menu parent: ["Content Management"]
-
1
actions :all
-
# menu :priority => 2
-
1
permit_params :question, :answer
-
-
1
index do
-
1
selectable_column
-
1
id_column
-
1
column :question do |setting|
-
1
raw(setting.question)
-
end
-
1
column :answer do |setting|
-
1
raw(setting.answer)
-
end
-
1
actions
-
end
-
-
1
form do |f|
-
1
f.inputs do
-
1
f.input :question
-
1
f.input :answer
-
end
-
1
f.actions
-
end
-
-
1
show do |d|
-
1
attributes_table do
-
1
row :question do |setting|
-
#raw(setting.question)
-
1
setting.question
-
end
-
1
row :answer do |setting|
-
1
raw(setting.answer)
-
end
-
end
-
end
-
end
-
1
module FileDocuments; end
-
-
1
ActiveAdmin.register BxBlockDatastorage::FileDocument, as: "Upload File" do
-
-
1
permit_params :title, :description, :document_type, :account_id, attachments: []
-
-
1
index do
-
selectable_column
-
id_column
-
column :title
-
column :description
-
column :document_type
-
column :created_at
-
column :updated_at
-
actions
-
end
-
-
1
form do |f|
-
f.inputs do
-
f.input :title,required: true
-
f.input :description,required: true
-
f.input :document_type, as: :select
-
f.input :account_id, label: "Account", as: :select, collection: AccountBlock::Account.all.map{ |acc| [acc.email, acc.id] }
-
f.input :attachments, as: :file, input_html: { multiple: true }
-
end
-
f.actions
-
end
-
-
1
show do
-
attributes_table do
-
row :title
-
row :description
-
row :document_type
-
row "Document files" do |obj|
-
ul do
-
if obj.attachments.attached?
-
obj.attachments.each do |file|
-
li do
-
ENV["HOST"] + Rails.application.routes.url_helpers.rails_blob_path(file, disposition: "attachment", only_path: true)
-
end
-
end
-
end
-
end
-
end
-
row :created_at
-
row :updated_at
-
# actions
-
end
-
end
-
end
-
1
ActiveAdmin.register BxBlockOrderManagement::Order, as: "All Orders" do
-
1
menu parent: ["Order Management"]
-
1
actions :all, except: [:new, :edit, :destroy]
-
-
1
permit_params :order_number, :amount, :status, :account_id, :total_tax, :order_status_id, :tax_charges, :confirmed_at, :cancelled_at, :placed_at, :order_date, :total
-
-
1
index do
-
1
selectable_column
-
1
id_column
-
1
column :order_number
-
1
column :amount
-
1
column :status
-
1
column :account_id
-
1
column :order_status_id
-
1
column :order_date
-
1
actions
-
end
-
-
1
show do
-
1
attributes_table do
-
1
row :order_number
-
1
row :amount
-
1
row :status
-
1
row :account_id
-
1
row :order_status_id
-
1
row :order_date
-
1
row :tax_charges
-
1
row :total_tax
-
1
row :confirmed_at
-
1
row :cancelled_at
-
1
row :placed_at
-
1
row :total
-
end
-
-
1
panel "Order Items" do
-
1
table_for resource.order_items do
-
1
column :id
-
1
column :quantity
-
1
column :unit_price
-
1
column :ebook_id
-
1
column :bundle_management_id
-
1
column :total_price
-
1
column :status
-
1
column :order_status_id
-
1
column :refunded_at
-
end
-
end
-
1
active_admin_comments
-
end
-
end
-
1
ActiveAdmin.register AccountBlock::Account, as: "Publishers" do
-
86
menu if: proc { current_admin_user.super_admin? }
-
-
1
actions :all
-
1
permit_params :first_name, :email, :full_phone_number, :user_type, :role_id, :publication_house_name, :bank_account_number, :ifsc_code
-
1
filter :email
-
-
1
controller do
-
1
def scoped_collection
-
4
AccountBlock::Account.joins(:role).where(roles: {name: "Publisher"})
-
end
-
-
1
def destroy
-
1
publisher = AccountBlock::Account.find(params[:id])
-
1
publisher.delete
-
1
redirect_to :admin_publishers
-
end
-
-
1
after_create do |account|
-
1
profile = BxBlockProfile::Profile.new(account_id: account.id)
-
1
profile.user_name = account.first_name
-
1
profile.full_phone_number = account.full_phone_number
-
1
profile.email = account.email
-
1
profile.publication_house_name = account.publication_house_name
-
1
profile.save
-
end
-
end
-
-
1
index do
-
1
id_column
-
1
column :name do |publisher|
-
4
publisher.first_name
-
end
-
1
column :phone_number do |publisher|
-
4
publisher.full_phone_number
-
end
-
1
column :role do |publisher|
-
4
publisher.role&.name
-
end
-
1
column :email
-
1
column :publication_house_name
-
1
column :bank_account_number
-
1
column :ifsc_code
-
1
actions
-
end
-
-
1
show do |cs|
-
1
attributes_table do
-
1
row :name do |publisher|
-
1
publisher.first_name
-
end
-
1
row :phone_number do |publisher|
-
1
publisher.full_phone_number
-
end
-
1
row :role do |publisher|
-
1
publisher.role&.name
-
end
-
1
row :email
-
1
row :publication_house_name
-
1
row :bank_account_number
-
1
row :ifsc_code
-
end
-
end
-
-
1
form do |f|
-
2
f.inputs do
-
2
f.input :role_id, as: :select, collection: BxBlockRolesPermissions::Role.where(name: "Publisher"), include_blank: false
-
2
f.input :first_name, label: "Name", required: true
-
2
f.input :publication_house_name
-
2
f.input :full_phone_number, label: "Phone Number", required: true
-
2
if !f.id.nil?
-
f.input :email, required: true, input_html: {readonly: true}
-
end
-
2
f.input :email, required: true
-
2
f.input :bank_account_number
-
2
f.input :ifsc_code
-
end
-
2
f.actions
-
end
-
end
-
1
ActiveAdmin.register BxBlockRolesPermissions::Role, as: "Role" do
-
1
actions :index, :show
-
-
1
permit_params :name
-
1
filter :name
-
-
1
controller do
-
1
def destroy
-
1
role = BxBlockRolesPermissions::Role.find(params[:id])
-
1
role.delete
-
1
redirect_to :admin_roles
-
end
-
end
-
-
1
index do
-
1
id_column
-
1
column :name
-
end
-
-
1
show do |role|
-
1
attributes_table do
-
1
row :name
-
end
-
end
-
-
1
form do |f|
-
f.inputs do
-
f.input :name
-
end
-
f.actions
-
end
-
end
-
1
ActiveAdmin.register_page "School Admin Analytics" do
-
1
menu parent: "Analytics"#, label: "School Admin Analytics"
-
-
1
content title: "School Admin Analytics" do
-
1
columns do
-
1
column do
-
1
panel "Total Students" do
-
1
ul do
-
1
li do
-
1
link_to AccountBlock::Account.joins(:role).where(roles: {name: "Student"}).size, admin_students_url()
-
end
-
end
-
end
-
1
panel "Total Teachers" do
-
1
ul do
-
1
li do
-
1
link_to AccountBlock::Account.joins(:role).where(roles: {name: "Teacher"}).size, admin_teachers_url()
-
end
-
end
-
end
-
end
-
-
1
column do
-
1
panel "Total Publishers" do
-
1
ul do
-
1
li do
-
1
link_to AccountBlock::Account.joins(:role).where(roles: {name: "Publisher"}).size, admin_publishers_url()
-
end
-
end
-
end
-
1
panel "Total Ebooks" do
-
1
ul do
-
1
li do
-
1
link_to "#{BxBlockBulkUploading::Ebook.all.count}", admin_ebooks_path
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
1
ActiveAdmin.register AccountBlock::Account, as: "SchoolAdminsPermission" do
-
1
menu if: proc { current_admin_user.super_admin? }
-
1
menu label: "MakePermissions"
-
-
1
actions :index, :show
-
1
permit_params :first_name, :email, :full_phone_number, :role_id, :school_id
-
1
filter :email
-
1
filter :school
-
-
-
1
action_item :back, only: [:show, :edit] do
-
1
link_to "Back", admin_school_url(AccountBlock::Account.find(params[:id]).school)
-
end
-
-
-
# action_item :add_sub_admin, only: [:show, :edit, :create]do
-
# link_to "Add Sub Admin", new_admin_sub_admin_user_path(school_id: resource.school&.id, email: resource.email)
-
# # link_to "Add Sub Admin", new_admin_sub_admin_user_path(school_id: resource.school_id, email: resource.email)
-
# end
-
1
action_item :add_sub_admin, only: [:show, :edit, :create] do
-
1
school_id = resource.school_id if resource.school_id.present?
-
1
school_name = resource.school&.name
-
1
link_to "Add Sub Admin", new_admin_sub_admin_user_path(school_id: school_id, school_name: school_name, email: resource.email)
-
end
-
-
-
-
1
controller do
-
1
def scoped_collection
-
2
AccountBlock::Account.joins(:role).where(roles: {name: "School Admin"})
-
end
-
end
-
-
1
index do
-
1
id_column
-
1
column :name do |school_admin|
-
4
school_admin.first_name
-
end
-
1
column :role do |school_admin|
-
4
school_admin.role&.name
-
end
-
1
column :school do |school_admin|
-
4
school_admin.school&.name
-
end
-
1
column :phone_number do |school_admin|
-
4
school_admin.full_phone_number
-
end
-
1
column :email
-
1
actions
-
end
-
-
1
show do
-
1
attributes_table do
-
1
row :name do |school_admin|
-
1
school_admin.first_name
-
end
-
1
row :role do |school_admin|
-
1
school_admin.role&.name
-
end
-
1
row :school do |school_admin|
-
1
school_admin.school&.name
-
end
-
1
row :phone_number do |school_admin|
-
1
school_admin.full_phone_number
-
end
-
1
row :email
-
end
-
end
-
end
-
-
1
ActiveAdmin.register AccountBlock::Account, as: "School Admins" do
-
1
menu false
-
1
actions :all
-
1
permit_params :first_name, :email, :full_phone_number, :role_id, :school_id
-
1
filter :email
-
-
1
action_item :back, only: [:show, :edit] do
-
1
link_to "Back", admin_school_url(AccountBlock::Account.find(params[:id]).school)
-
end
-
-
1
controller do
-
1
def scoped_collection
-
5
AccountBlock::Account.joins(:role).where(roles: {name: "School Admin"})
-
end
-
-
1
def destroy
-
1
school_admin = AccountBlock::Account.find(params[:id])
-
1
school = school_admin.school
-
1
school_admin.delete
-
1
redirect_to admin_school_url(school)
-
end
-
-
1
after_create do |account|
-
1
profile = BxBlockProfile::Profile.new(account_id: account.id)
-
1
profile.user_name = account.first_name
-
1
profile.email = account.email
-
1
profile.full_phone_number = account.full_phone_number
-
# profile.employee_unique_id = account.employee_unique_id
-
1
profile.save
-
end
-
-
1
def create
-
1
create! do |format|
-
1
if resource.errors.present?
-
redirect_to new_admin_school_admin_path(school_id: params[:account][:school_id], format: :html), notice: "School Admin email id must be unique" and return
-
else
-
1
redirect_to admin_school_path(resource.school_id), notice: "School Admin created successfully." and return
-
end
-
end
-
end
-
-
1
def update
-
1
update! do |format|
-
1
if resource.errors.present?
-
render :edit, location: edit_admin_school_admin_path(school_id: params[:account][:school_id])
-
return
-
else
-
1
redirect_to admin_school_path(resource.school_id), notice: "School Admin updated successfully." and return
-
end
-
end
-
end
-
end
-
-
1
index do
-
1
id_column
-
1
column :name do |school_admin|
-
4
school_admin.first_name
-
end
-
1
column :role do |school_admin|
-
4
school_admin.role&.name
-
end
-
1
column :school do |school_admin|
-
4
school_admin.school&.name
-
end
-
1
column :phone_number do |school_admin|
-
4
school_admin.full_phone_number
-
end
-
1
column :email
-
1
actions
-
end
-
-
1
show do
-
1
attributes_table do
-
1
row :name do |school_admin|
-
1
school_admin.first_name
-
end
-
1
row :role do |school_admin|
-
1
school_admin.role&.name
-
end
-
1
row :school do |school_admin|
-
1
school_admin.school&.name
-
end
-
1
row :phone_number do |school_admin|
-
1
school_admin.full_phone_number
-
end
-
1
row :email
-
end
-
end
-
-
1
form do |f|
-
1
f.inputs do
-
1
f.input :role_id, as: :select, collection: BxBlockRolesPermissions::Role.where(name: "School Admin"), include_blank: false
-
1
f.input :school_id, as: :select, collection: BxBlockCategories::School.where(id: params[:school_id].to_i), include_blank: false
-
1
f.input :first_name, label: "Name", required: true
-
1
f.input :full_phone_number, label: "Phone Number", required: true
-
1
if !f.id.nil?
-
f.input :email, required: true, input_html: {readonly: true}
-
else
-
1
f.input :email, required: true
-
end
-
end
-
1
f.actions do
-
1
f.action :submit, label: "Save"
-
end
-
end
-
end
-
1
ActiveAdmin.register BxBlockCategories::SchoolClass, as: "Class" do
-
1
menu false
-
-
1
permit_params :id, :class_number, :school_id, :account_id, class_divisions_attributes: [:id, :division_name, :account_id]
-
-
1
action_item :back, only: [:new, :show, :edit] do
-
4
school_id = resource&.school_id || params[:school_id]
-
4
if school_id
-
3
link_to 'Back to School View', admin_school_path(school_id), class: 'button'
-
else
-
1
link_to 'Back to School View', admin_schools_path, class: 'button'
-
end
-
end
-
-
1
after_save do |school_class|
-
3
school_class.class_divisions.each do |division|
-
3
division.update(school_id: school_class.school_id)
-
3
AccountBlock::Account.find_by(id: division.account_id)&.update(class_division_id: division.id, school_class_id: school_class.id)
-
end
-
end
-
-
1
controller do
-
1
def destroy
-
3
school_id = resource.school_id
-
3
resource.class_divisions&.each do |divi|
-
3
AccountBlock::Account.where(role_id: BxBlockRolesPermissions::Role.find_by(name: 'Student').id, class_division_id: divi.id).delete_all
-
3
divi.subject_teacher_ids.each do |account|
-
5
account = AccountBlock::Account.find_by(id: account)
-
5
account.subject_teacher_division_ids = account.subject_teacher_division_ids - [divi.id]
-
5
account.subject_teacher_class_ids = account.subject_teacher_class_ids - [resource.id]
-
5
account.save
-
end
-
end
-
3
resource.class_divisions.delete_all
-
3
AccountBlock::Account.where(role_id: BxBlockRolesPermissions::Role.find_by(name: 'Teacher').id, school_class_id: resource&.id)&.update(school_class_id: nil, class_division_id: nil)
-
3
resource.destroy
-
3
redirect_to admin_school_path(school_id), notice: "Class deleted successfully."
-
end
-
-
1
def create
-
3
divisions_params = params[:school_class][:class_divisions_attributes]&.values
-
8
division_names = divisions_params&.map { |division| division[:division_name] }
-
8
division_teacher_accounts = divisions_params&.map { |division| division[:account_id] }
-
3
if params["school_class"]["class_number"].present? && division_names&.uniq&.length.to_i < division_names&.length.to_i
-
1
flash[:error] = 'Division name must be unique within the class.'
-
1
redirect_to new_admin_class_path
-
1
return
-
2
elsif params["school_class"]["class_number"].present? && division_teacher_accounts&.uniq&.length.to_i < division_teacher_accounts&.length.to_i
-
1
flash[:error] = 'Class Teacher must be unique within the class division of class.'
-
1
redirect_to new_admin_class_path
-
1
return
-
end
-
1
super
-
end
-
-
1
def update
-
4
divisions_params = params[:school_class][:class_divisions_attributes]&.values
-
8
division_names = divisions_params&.map { |division| division[:division_name] }
-
8
division_teacher_accounts = divisions_params&.map { |division| division[:account_id] }
-
4
if params["school_class"]["class_number"].present? && division_names&.uniq&.length.to_i < division_names&.length.to_i
-
1
flash[:error] = 'Division name must be unique within the class.'
-
1
redirect_to edit_admin_class_path
-
1
return
-
3
elsif params["school_class"]["class_number"].present? && division_teacher_accounts&.uniq&.length.to_i < division_teacher_accounts&.length.to_i
-
1
flash[:error] = 'Class Teacher must be unique within the class division of class.'
-
1
redirect_to edit_admin_class_path
-
1
return
-
end
-
2
super
-
end
-
end
-
-
1
index do
-
1
id_column
-
1
column :class_number
-
1
column :school_id do |cs|
-
-
1
BxBlockCategories::School.find_by(id: cs&.school_id)&.name
-
end
-
1
actions
-
end
-
-
1
show title: "Classes" do |cs|
-
1
attributes_table do
-
1
row :school do |cs|
-
1
BxBlockCategories::School.find(cs.school_id).name
-
end
-
1
row :class_number
-
1
panel "Class Division" do
-
1
class_divisions = BxBlockCategories::ClassDivision.where(school_class_id: params[:id])
-
1
render "/admin/class_division/index", locals: { class_divisions: class_divisions }, layout: "active_admin"
-
end
-
end
-
end
-
-
1
form do |f|
-
5
f.inputs do
-
5
if f.object.new_record?
-
3
f.input :class_number, as: :select, collection: 1..12
-
else
-
2
f.input :class_number, as: :select, collection: [[f.object.class_number, f.object.class_number]], include_blank: false
-
end
-
5
school_collection = if f.object && !f.object.new_record?
-
2
BxBlockCategories::School.where(id: f.object.school_id)
-
else
-
3
BxBlockCategories::School.where(id: params[:school_id].to_i)
-
end
-
5
f.input :school_id, as: :select, collection: school_collection, include_blank: false
-
end
-
-
5
f.inputs 'Class Division' do
-
5
f.has_many :class_divisions, heading: 'Add Class Divisions', allow_destroy: true, new_record: 'Add Division' do |division|
-
9
division.input :division_name, required: true
-
9
school = BxBlockCategories::School.find_by(id: f.object.school_id)
-
9
account_collection = if division.object.persisted?
-
2
AccountBlock::Account.where(role_id: BxBlockRolesPermissions::Role.find_by(name: "Teacher"), class_division_id: division.object.id).pluck(:email, :id)
-
7
elsif school
-
5
AccountBlock::Account.where(role_id: BxBlockRolesPermissions::Role.find_by(name: "Teacher"), school_id: school.id, class_division_id: nil).pluck(:email, :id)
-
else
-
2
AccountBlock::Account.where(role_id: BxBlockRolesPermissions::Role.find_by(name: "Teacher"), school_id: params[:school_id], school_class_id: params[:id], class_division_id: nil).pluck(:email, :id)
-
end
-
9
division.input :account_id, label: "Class Teacher", as: :select, collection: account_collection, required: true
-
end
-
5
f.semantic_errors :base
-
end
-
-
5
f.actions do
-
5
if resource.persisted?
-
2
f.action :submit, as: :button, label: 'Update School Class'
-
2
f.action :cancel
-
else
-
3
f.action :submit, label: "Save"
-
3
f.action :cancel
-
end
-
end
-
-
end
-
end
-
1
ActiveAdmin.register BxBlockCategories::School, as: "Schools" do
-
-
1
actions :all
-
-
1
permit_params :name, :email, :board, :phone_number, :principal_name
-
1
filter :email
-
-
1
index do
-
1
id_column
-
1
column :name
-
1
column :email
-
1
column :principal_name
-
1
column :phone_number
-
1
column :board
-
1
actions
-
end
-
-
1
show do |cs|
-
1
attributes_table do
-
1
row :name
-
1
row :email
-
1
row :principal_name
-
1
row :phone_number
-
1
row :board
-
end
-
-
1
panel "Classes" do
-
1
panel link_to 'New School Class', new_admin_class_url(school_id: params[:id]) do
-
end
-
1
school_classes = BxBlockCategories::SchoolClass.where(school_id: params[:id])
-
1
render "/admin/school_class/index" , :locals => {school_classes: school_classes}, layout: "active_admin"
-
end
-
-
1
panel "School Admins" do
-
1
panel link_to 'New School Admin', new_admin_school_admin_url(school_id: params[:id]) do
-
end
-
1
school_admins = AccountBlock::Account.joins(:role).where(roles: {name: "School Admin"}).where(school_id: params[:id])
-
1
render "/admin/school_admin/index", :locals => {school_admins: school_admins}, layout: "active_admin"
-
end
-
-
1
panel "Teachers" do
-
1
panel link_to 'New Teacher', new_admin_teacher_url(school_id: params[:id]) do
-
end
-
1
teachers = AccountBlock::Account.joins(:role).where(roles: {name: "Teacher"}).where(school_id: params[:id])
-
1
render "/admin/teacher/index", :locals => {teachers: teachers}, layout: "active_admin"
-
end
-
end
-
-
1
form do |f|
-
1
f.inputs do
-
1
f.input :name
-
1
f.input :email
-
1
f.input :principal_name
-
1
f.input :phone_number
-
1
f.input :board
-
end
-
1
f.actions
-
end
-
-
1
controller do
-
1
def destroy
-
1
resource.school_classes.flat_map(&:class_divisions).each do |div|
-
AccountBlock::Account.where(role_id: BxBlockRolesPermissions::Role.find_by(name: 'Student').id, class_division_id: div&.id).delete_all
-
end
-
1
AccountBlock::Account.where(role_id: BxBlockRolesPermissions::Role.find_by(name: 'Teacher').id, school_id: resource&.id).delete_all
-
# resource.school_classes&.flat_map(&:class_divisions)&.delete_all
-
1
class_divisions = resource.school_classes&.flat_map(&:class_divisions)
-
1
class_divisions&.each(&:destroy) if class_divisions.present?
-
1
resource.school_classes&.delete_all
-
1
resource.accounts.where(role_id: BxBlockRolesPermissions::Role.find_by(name: "School Admin")).delete_all
-
1
resource.destroy
-
1
redirect_to admin_schools_path, notice: "School deleted successfully."
-
end
-
-
end
-
end
-
1
ActiveAdmin.register AccountBlock::Account, as: "Students" do
-
1
menu false
-
1
actions :all
-
-
1
permit_params :first_name, :last_name, :full_phone_number, :user_type, :guardian_email, :role_id, :school_id, :student_unique_id, :class_division_id, :school_class_id
-
1
filter :guardian_email
-
-
1
action_item :back, only: [:new, :show, :edit] do
-
3
if resource&.class_division_id.present?
-
2
link_to 'Back', admin_class_division_path(resource.class_division_id)
-
1
else params[:class_division_id]&.present?
-
1
link_to 'Back', admin_class_division_path(params[:class_division_id])
-
end
-
end
-
-
1
controller do
-
# def scoped_collection
-
# AccountBlock::Account.joins(:role).where(roles: {name: "Student"})
-
# end
-
-
1
def scoped_collection
-
7
if current_admin_user.super_admin?
-
7
AccountBlock::Account.joins(:role).where(roles: { name: "Student" })
-
else
-
AccountBlock::Account.joins(:role).where(roles: { name: "Student" }).where(school_id: current_admin_user.school_id)
-
end
-
end
-
-
1
def destroy
-
1
student = AccountBlock::Account.find(params[:id])
-
1
student.delete
-
1
redirect_to admin_class_division_path(student.class_division_id), notice: "Student deleted successfully."
-
end
-
-
1
after_create do |account|
-
2
profile = BxBlockProfile::Profile.new(account_id: account.id)
-
2
profile.user_name = account.first_name
-
2
profile.guardian_contact_no = account.full_phone_number
-
2
profile.student_unique_id = account.student_unique_id
-
2
profile.guardian_email = account.guardian_email
-
2
profile.save
-
end
-
-
1
def create
-
2
create! do |format|
-
2
if resource.errors.present?
-
2
class_division_id = params[:account]&.dig(:class_division_id) || resource.class_division_id
-
2
redirect_to new_admin_student_path(class_division_id: class_division_id, school_class_id: params[:account][:school_class_id], school_id: params[:account][:school_id], format: :html), notice: "Student Id must be unique" and return
-
else
-
redirect_to admin_class_division_path(resource.class_division_id), notice: "Student created successfully." and return
-
end
-
end
-
end
-
-
1
def update
-
1
update! do |format|
-
1
if resource.errors.present?
-
render :edit, location: edit_admin_student_path(class_division_id: params[:account][:class_division_id], school_class_id: params[:account][:school_class_id], school_id: params[:account][:school_id])
-
return
-
else
-
1
redirect_to admin_class_division_path(resource.class_division_id), notice: "Student updated successfully." and return
-
end
-
end
-
end
-
end
-
-
1
index do
-
1
id_column
-
1
column :name do |student|
-
4
student.first_name
-
end
-
1
column :guardian_email
-
1
column :phone_number do |student|
-
4
student.full_phone_number
-
end
-
1
column :role do |student|
-
4
student.role&.name
-
end
-
1
column :student_unique_code do |student|
-
4
student.student_unique_id
-
end
-
-
1
column :school do |student|
-
4
student.school&.name
-
end
-
1
actions
-
end
-
-
1
show do |cs|
-
1
attributes_table do
-
1
row :name do |student|
-
1
student.first_name
-
end
-
1
row :guardian_email
-
1
row :phone_number do |student|
-
1
student.full_phone_number
-
end
-
1
row :role do |student|
-
1
student.role&.name
-
end
-
-
1
row :student_unique_code do |student|
-
1
student.student_unique_id
-
end
-
-
1
row :school do |student|
-
1
student.school&.name
-
end
-
end
-
end
-
-
1
form do |f|
-
2
f.inputs do
-
2
f.input :role_id, as: :select, collection: BxBlockRolesPermissions::Role.where(name: "Student"), include_blank: false
-
# f.input :school_id, as: :select, collection: BxBlockCategories::School.all, include_blank: false
-
2
school_collection = if f.object && !f.object.new_record?
-
1
BxBlockCategories::School.where(id: f.object.school_id)
-
else
-
1
BxBlockCategories::School.where(id: params[:school_id].to_i)
-
end
-
2
f.input :school_id, as: :select, collection: school_collection, include_blank: false
-
2
class_collection = if f.object.new_record?
-
1
BxBlockCategories::SchoolClass.where(id: params[:school_class_id]).pluck(:class_number, :id)
-
1
else f.object.school_class_id.blank?
-
1
BxBlockCategories::SchoolClass.where(id: f.object.school_class_id).pluck(:class_number, :id)
-
end
-
2
f.input :school_class_id, as: :select, label: "Class", collection: class_collection, include_blank: false
-
2
class_division_collection = if f.object.new_record?
-
1
BxBlockCategories::ClassDivision.where(id: params[:class_division_id]).pluck(:division_name, :id)
-
1
else f.object.class_division_id.blank?
-
1
BxBlockCategories::ClassDivision.where(id: f.object.class_division_id).pluck(:division_name, :id)
-
end
-
2
f.input :class_division_id, as: :select, collection: class_division_collection, include_blank: false
-
2
f.input :first_name, label: "Name", required: true
-
2
f.input :student_unique_id, label: "Student Unique Code", required: true
-
2
if !f.id.nil?
-
f.input :guardian_email, required: true, input_html: {readonly: true}
-
end
-
2
f.input :guardian_email, required: true
-
2
f.input :full_phone_number, label: "Phone Number", required: true
-
end
-
2
f.actions do
-
2
f.action :submit, label: "Save"
-
end
-
end
-
end
-
1
module AdminUsers
-
1
class Load
-
1
@@loaded_from_gem = false
-
1
def self.is_loaded_from_gem
-
1
@@loaded_from_gem
-
end
-
-
# def self.loaded
-
# end
-
-
# Check if this file is loaded from gem directory or not
-
# The gem directory looks like
-
# /template-app/.gems/gems/bx_block_custom_user_subs-0.0.7/app/admin/subscription.rb
-
# if it has block's name in it then it's a gem
-
1
@@loaded_from_gem = Load.method('loaded').source_location.first.include?('bx_block_')
-
end
-
end
-
-
1
unless AdminUsers::Load.is_loaded_from_gem
-
1
ActiveAdmin.register AdminUser, as: "SubAdminUser" do
-
1
menu label: "Edit Permission"
-
1
permit_params :email, :role, :school_id, :password, :password_confirmation, :school_allow, :class_allow, :subject_allow, :assignment_allow, :video_allow, :account_allow
-
-
1
index do
-
2
selectable_column
-
2
id_column
-
2
column :email
-
2
column :school_id
-
2
column :school_name do |resource|
-
2
school = BxBlockCategories::School.find_by(id: resource.school_id)
-
2
school.name if school
-
end
-
2
column :role
-
2
column :current_sign_in_at
-
2
column :sign_in_count
-
2
column :created_at
-
2
actions
-
end
-
-
1
filter :email
-
3
filter :school_id, as: :select, collection: proc { BxBlockCategories::School.pluck(:name, :id) }
-
-
1
filter :current_sign_in_at
-
1
filter :sign_in_count
-
1
filter :created_at
-
-
1
before_build do |admin_user|
-
1
admin_user.role ||= :sub_admin
-
end
-
-
1
form do |f|
-
1
f.inputs do
-
1
f.input :role, as: :hidden
-
1
school_id = params[:school_id] || f.object.school_id
-
1
school_name = BxBlockCategories::School.find_by(id: school_id)&.name
-
1
f.input :school_id, input_html: { value: school_id, readonly: true }, as: :hidden
-
1
f.input :school_name, input_html: { value: school_name, readonly: true }
-
-
-
1
f.input :email, input_html: { value: params[:email] || f.object.email, readonly: true }
-
# f.input :school_id, input_html: { value: f.object.school_id, readonly: true }
-
# f.input :email, input_html: { value: f.object.email, readonly: true }
-
-
1
f.input :password
-
1
f.input :password_confirmation
-
-
1
f.input :school_allow, as: :boolean
-
1
f.input :class_allow, as: :boolean
-
1
f.input :subject_allow, as: :boolean
-
1
f.input :assignment_allow, as: :boolean
-
1
f.input :video_allow, as: :boolean
-
1
f.input :account_allow, as: :boolean
-
end
-
1
f.actions
-
end
-
-
1
controller do
-
1
def scoped_collection
-
3
AdminUser.where(role: :sub_admin)
-
end
-
end
-
end
-
end
-
1
ActiveAdmin.register BxBlockCatalogue::Subject, as: "Subject" do
-
1
permit_params :id, :subject_name
-
-
1
index do
-
1
selectable_column
-
1
id_column
-
1
column :subject_name
-
1
actions
-
end
-
-
1
form do |f|
-
1
f.semantic_errors(*f.object.errors.keys)
-
1
f.inputs do
-
1
f.input :subject_name
-
end
-
1
f.actions
-
end
-
-
1
show title: "Subject" do
-
1
attributes_table do
-
1
row :id
-
1
row :subject_name
-
end
-
end
-
-
end
-
1
ActiveAdmin.register BxBlockCatalogue::SubjectManagement, as: "Subject And Teacher" do
-
1
menu false
-
1
actions :all, except: [:edit]
-
1
permit_params :id, :subject_id, :account_id , :class_division_id, :school_class_id, :school_id
-
-
1
action_item :back, only: :show do
-
1
link_to 'Back to Class Division', admin_class_division_path(resource&.class_division_id), class: 'button'
-
end
-
-
-
1
controller do
-
1
def destroy
-
1
resource.class_division&.subject_ids = resource&.class_division&.subject_ids - [resource&.subject_id]
-
1
resource.account&.subject_teacher_division_ids = resource.account&.subject_teacher_division_ids - [resource.class_division&.school_class.id]
-
1
resource.account&.subject_teacher_class_ids = resource.account&.subject_teacher_class_ids - [resource&.class_division_id]
-
1
resource.account&.save
-
1
resource&.class_division&.save
-
1
class_division_id = resource&.class_division_id
-
1
resource.destroy
-
1
redirect_to admin_class_division_path(class_division_id), notice: "Subject deleted from class successfully."
-
end
-
end
-
-
1
index do
-
1
selectable_column
-
1
id_column
-
1
column "Subject" do |subj|
-
1
subj.subject.subject_name rescue nil
-
end
-
1
column "Teacher" do |tech|
-
1
tech.account.email rescue nil
-
end
-
1
actions
-
end
-
-
# form do |f|
-
# f.semantic_errors(*f.object.errors.keys)
-
# f.inputs do
-
# selected_subject_ids = resource.subject_ids || []
-
# available_subjects = BxBlockCatalogue::Subject.where.not(id: selected_subject_ids)
-
# f.input :subject_id, as: :select, label: "Subject", collection: available_subjects.pluck(:subject_name, :id), selected: selected_subject_ids
-
-
# selected_teacher_ids = resource.subject_teacher_ids || []
-
# available_teachers = AccountBlock::Account.where(role_id: BxBlockRolesPermissions::Role.find_by(name: "Teacher")).where.not(id: selected_teacher_ids)
-
# f.input :account_id, as: :select, label: "Subject Teacher", collection: available_teachers.pluck(:email, :id), selected: selected_teacher_ids
-
-
# end
-
# f.actions
-
# end
-
-
1
show title: "Subject" do
-
1
attributes_table do
-
1
row :id
-
1
row "Subject" do
-
1
resource.subject.subject_name rescue nil
-
end
-
1
row "Teacher" do
-
1
resource.account.email rescue nil
-
end
-
-
1
panel "Video Lecture" do
-
1
panel link_to 'Add Video Lecture', new_admin_video_lecture_url(subject_id: resource.subject_id, subject_management_id: resource&.id, school_class_id: resource&.class_division.school_class_id, school_id: resource&.class_division.school_id, class_division_id: resource&.class_division_id, account_id: resource&.account_id) do
-
1
videos = BxBlockCatalogue::VideosLecture.where(subject_management_id: resource.id)
-
1
render "/admin/subject_and_teacher/video", locals: { videos: videos }, layout: "active_admin"
-
end
-
end
-
-
1
panel "Assigment" do
-
1
panel link_to 'Add Assigment', new_admin_assignment_url(subject_id: resource.subject_id, subject_management_id: resource&.id, school_class_id: resource&.class_division.school_class_id, school_id: resource&.class_division.school_id, class_division_id: resource&.class_division_id, account_id: resource&.account_id) do
-
1
assignments = BxBlockCatalogue::Assignment.where(subject_management_id: resource.id)
-
1
render "/admin/subject_and_teacher/assignment", locals: { assignments: assignments }, layout: "active_admin"
-
end
-
end
-
end
-
end
-
-
end
-
1
ActiveAdmin.register AccountBlock::Account, as: "Teachers" do
-
1
menu false
-
1
actions :all
-
1
permit_params :first_name, :last_name, :email, :full_phone_number, :user_type, :teacher_unique_id, :role_id, :school_id, :department, :class_division_id, :school_class_id
-
1
filter :email
-
-
1
action_item :back, only: [:new, :show, :edit] do
-
3
if params[:id].present?
-
2
link_to 'Back', admin_school_url(AccountBlock::Account.find(params[:id]).school)
-
else
-
1
link_to 'Back', admin_school_url(params[:school_id])
-
end
-
end
-
-
1
controller do
-
1
def scoped_collection
-
7
if current_admin_user.super_admin?
-
7
AccountBlock::Account.joins(:role).where(roles: {name: "Teacher"})
-
else
-
AccountBlock::Account.joins(:role).where(roles: { name: "Teacher" }).where(school_id: current_admin_user.school_id)
-
end
-
end
-
1
def destroy
-
1
teacher = AccountBlock::Account.find(params[:id])
-
1
school = teacher.school
-
1
teacher.delete
-
1
redirect_to admin_school_url(school)
-
end
-
-
1
after_create do |account|
-
2
profile = BxBlockProfile::Profile.new(account_id: account.id)
-
2
profile.user_name = account.first_name
-
2
profile.email = account.email
-
2
profile.full_phone_number = account.full_phone_number
-
2
profile.teacher_unique_id = account.teacher_unique_id
-
2
profile.save
-
end
-
-
1
def create
-
2
create! do |format|
-
2
if resource.errors.present?
-
redirect_to new_admin_teacher_path(school_id: params[:account][:school_id], format: :html), notice: "Teacher email id must be unique" and return
-
else
-
2
redirect_to admin_school_path(resource.school_id), notice: "Teacher created successfully." and return
-
end
-
end
-
end
-
-
1
def update
-
1
update! do |format|
-
1
if resource.errors.present?
-
render :edit, location: edit_admin_teacher_path(school_id: params[:account][:school_id])
-
return
-
else
-
1
redirect_to admin_school_path(resource.school_id), notice: "Teacher updated successfully." and return
-
end
-
end
-
end
-
end
-
-
1
index do
-
1
id_column
-
1
column :name do |teacher|
-
5
teacher.first_name
-
end
-
1
column :email
-
1
column :phone_number do |teacher|
-
5
teacher.full_phone_number
-
end
-
1
column :role do |teacher|
-
5
teacher.role&.name
-
end
-
1
column :school do |teacher|
-
5
teacher.school&.name
-
end
-
1
column :teacher_unique_code do |teacher|
-
5
teacher.teacher_unique_id
-
end
-
1
column :department
-
1
actions
-
end
-
-
1
show do |cs|
-
1
attributes_table do
-
1
row :name do |teacher|
-
1
teacher.first_name
-
end
-
1
row :email
-
1
row :phone_number do |teacher|
-
1
teacher.full_phone_number
-
end
-
1
row :role do |teacher|
-
1
teacher.role&.name
-
end
-
1
row :school do |teacher|
-
1
teacher.school&.name
-
end
-
1
row :teacher_unique_code do |teacher|
-
1
teacher.teacher_unique_id
-
end
-
1
row :department
-
end
-
end
-
-
1
form do |f|
-
2
f.inputs do
-
2
f.input :role_id, as: :select, collection: BxBlockRolesPermissions::Role.where(name: "Teacher"), include_blank: false
-
# f.input :school_id, as: :select, collection: BxBlockCategories::School.where(id: params[:school_id].to_i), include_blank: false
-
2
school_collection = if f.object && !f.object.new_record?
-
1
BxBlockCategories::School.where(id: f.object.school_id)
-
else
-
1
BxBlockCategories::School.where(id: params[:school_id].to_i)
-
end
-
2
f.input :school_id, as: :select, collection: school_collection, include_blank: false
-
2
f.input :first_name, label: "Name", required: true
-
2
if !f.id.nil?
-
f.input :email, required: true, input_html: {readonly: true}
-
end
-
2
f.input :email, required: true
-
2
f.input :teacher_unique_id, label: "Teacher Unique code", required: true
-
2
f.input :full_phone_number, label: "Phone Number", required: true
-
2
f.input :department
-
end
-
2
f.actions do
-
2
f.action :submit, label: "Save"
-
end
-
end
-
end
-
1
ActiveAdmin.register BxBlockTermsAndConditions::TermsAndCondition, as: "Terms And Condition" do
-
# actions :all, only: :show, except: [:new, :destroy]
-
1
menu parent: ["Content Management"]
-
1
permit_params :name, :description
-
-
1
index do
-
1
selectable_column
-
1
id_column
-
1
column :name do |setting|
-
1
raw(setting.name)
-
end
-
1
column :description do |setting|
-
1
raw(setting.description)
-
end
-
1
actions
-
end
-
-
1
form do |f|
-
1
f.semantic_errors
-
1
f.inputs do
-
1
f.input :name
-
1
f.input :description#, as: :ckeditor
-
end
-
1
f.actions
-
end
-
-
1
show do |d|
-
1
attributes_table do
-
1
row :name do |setting|
-
#raw(setting.name)
-
1
setting.name
-
end
-
1
row :description do |setting|
-
1
raw(setting.description)
-
end
-
end
-
end
-
end
-
1
ActiveAdmin.register BxBlockCatalogue::VideosLecture, as: "Video Lecture" do
-
1
menu false
-
1
permit_params :id, :video, :title, :subject, :description, :subject_id, :subject_management_id, :class_division_id, :school_id, :school_class_id, :account_id, :time_hour, :time_min
-
-
1
action_item :back, only: [:new, :show, :edit] do
-
3
@subject_management_id = resource&.subject_management_id || params[:subject_management_id]
-
3
link_to 'Back', admin_subject_and_teacher_path(@subject_management_id), class: 'button'
-
end
-
-
1
controller do
-
1
def destroy
-
1
@subject_management_id = resource&.subject_management_id
-
1
resource.destroy
-
1
redirect_to admin_subject_and_teacher_path(@subject_management_id), notice: "This video lecture is delete successfully."
-
end
-
-
1
def create
-
1
create! do |format|
-
1
if resource.valid?
-
redirect_to admin_subject_and_teacher_path(resource&.subject_management_id), notice: "Video Lecture created successfully." and return
-
else
-
1
handle_video_errors
-
1
redirect_to new_admin_video_lecture_path(subject_id: params[:videos_lecture][:subject_id], subject_management_id: params[:videos_lecture][:subject_management_id], class_division_id: params[:videos_lecture][:class_division_id], account_id: params[:videos_lecture][:account_id], format: :html) and return
-
end
-
end
-
end
-
-
1
def update
-
2
update! do |format|
-
2
if resource.errors.present?
-
render :edit, location: edit_admin_video_lecture_path(subject_id: params[:videos_lecture][:subject_id], subject_management_id: params[:videos_lecture][:subject_management_id], class_division_id: params[:videos_lecture][:class_division_id], account_id: params[:videos_lecture][:account_id])
-
return
-
else
-
2
redirect_to admin_subject_and_teacher_path(resource&.subject_management_id), notice: "Video Lecture updated successfully." and return
-
end
-
end
-
end
-
-
1
private
-
-
1
def handle_video_errors
-
1
if resource.errors.include?(:video)
-
1
flash[:error] = resource.errors[:video].join(', ')
-
else
-
flash[:error] = 'Please enter data in mandatory fields'
-
end
-
end
-
-
end
-
-
1
index do
-
1
selectable_column
-
1
id_column
-
1
column :title
-
1
column :subject_id do |video|
-
1
BxBlockCatalogue::Subject.find(video.subject_id).subject_name rescue nil
-
end
-
1
column :description
-
1
column :video do |resource|
-
1
link_to resource.video, resource.video, target: '_blank'
-
end
-
1
actions
-
end
-
-
1
form do |f|
-
2
f.semantic_errors(*f.object.errors.keys)
-
2
f.inputs do
-
2
f.input :title
-
2
subject = if f.object.new_record?
-
1
BxBlockCatalogue::Subject.where(id: params[:subject_id].to_i)
-
else
-
1
BxBlockCatalogue::Subject.where(id: f.object.subject_id)
-
end
-
2
f.input :subject_id, as: :select, collection: subject.pluck(:subject_name, :id), include_blank: false
-
2
f.input :description
-
-
2
if f.object.new_record?
-
1
f.input :video
-
1
f.input :time_hour, as: :select, collection: 0..23
-
1
f.input :time_min, as: :select, collection: 0..59
-
1
f.input :subject_management_id, as: :hidden, input_html: { value: params[:subject_management_id] }
-
1
f.input :class_division_id, as: :hidden, input_html: { value: params[:class_division_id] }
-
1
f.input :school_class_id, as: :hidden, input_html: { value: params[:school_class_id] }
-
1
f.input :school_id, as: :hidden, input_html: { value: params[:school_id] }
-
1
f.input :account_id, as: :hidden, input_html: { value: params[:account_id] }
-
else
-
1
f.input :video do
-
link_to 'Watch Video', f.object.video, target: '_blank'
-
end
-
1
f.input :time_hour, as: :select, collection: 0..23, input_html: { value: f.object.time_hour }
-
1
f.input :time_min, as: :select, collection: 0..59, input_html: { value: f.object.time_min }
-
1
f.input :subject_management_id, as: :hidden, input_html: { value: f.object.subject_management_id }
-
1
f.input :class_division_id, as: :hidden, input_html: { value: f.object.class_division_id }
-
1
f.input :school_class_id, as: :hidden, input_html: { value: f.object.school_class_id }
-
1
f.input :school_id, as: :hidden, input_html: { value: f.object.school_id }
-
1
f.input :account_id, as: :hidden, input_html: { value: f.object.account_id }
-
end
-
end
-
2
f.actions do
-
2
if resource.persisted?
-
1
f.action :submit, as: :button, label: 'Update Videos Lecture'
-
1
f.action :cancel
-
else
-
1
f.action :submit, label: "Create Videos Lecture"
-
1
f.action :cancel
-
end
-
end
-
end
-
-
1
show do
-
1
attributes_table do
-
1
row :id
-
1
row :title
-
1
row :subject_id do |video|
-
1
BxBlockCatalogue::Subject.find(video.subject_id).subject_name rescue nil
-
end
-
1
row :description
-
1
row :video do |resource|
-
1
link_to resource.video, resource.video, target: '_blank'
-
end
-
1
row :time_hour
-
1
row :time_min
-
end
-
end
-
-
end
-
module BxBlockProfile
-
module ChangePasswordCommand
-
extend self
-
-
def execute(account_id, password, new_password)
-
validator = ChangePasswordValidator
-
.new(account_id, password, new_password)
-
-
account = validator.account
-
-
unless validator.valid?
-
return [:unprocessable_entity, validator.errors.full_messages]
-
end
-
return [:created, account] if update_password(account, new_password)
-
[:unprocessable_entity, ['Password could not be saved']]
-
end
-
-
private
-
-
def update_password(account, new_password)
-
account.update :password => new_password
-
end
-
end
-
end
-
module BxBlockProfile
-
module UpdateAccountCommand
-
extend self
-
-
def execute(account_id, params)
-
validator = UpdateAccountValidator.new(account_id, params)
-
-
unless validator.valid?
-
return [:unprocessable_entity, validator.errors.full_messages]
-
end
-
-
account = validator.account
-
attrs = validator.attributes
-
return [:ok, account.reload] if account.update(attrs)
-
-
-
[:unprocessable_entity, [account.errors.full_messages.first]]
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
1
module BxBlockAppointmentManagement
-
1
module PatchAccountBlock
-
1
extend ActiveSupport::Concern
-
1
included do
-
1
has_many :availabilities, foreign_key: :service_provider_id, class_name: "BxBlockAppointmentManagement::Availability"
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
1
module BuilderJsonWebToken
-
1
module JsonWebTokenValidation
-
ERROR_CLASSES = [
-
1
JWT::DecodeError,
-
JWT::ExpiredSignature,
-
].freeze
-
-
1
private
-
-
1
def validate_json_web_token
-
141
token = request.headers[:token] || params[:token]
-
-
begin
-
141
@token = JsonWebToken.decode(token)
-
rescue *ERROR_CLASSES => exception
-
handle_exception exception
-
end
-
end
-
-
1
def handle_exception(exception)
-
# order matters here
-
# JWT::ExpiredSignature appears to be a subclass of JWT::DecodeError
-
case exception
-
when JWT::ExpiredSignature
-
return render json: { errors: [token: 'Token has Expired'] },
-
status: :unauthorized
-
when JWT::DecodeError
-
return render json: { errors: [token: 'Invalid token'] },
-
status: :bad_request
-
end
-
end
-
end
-
end
-
1
module BxBlockAccountGroups
-
1
module PatchAccountAssociations
-
1
extend ActiveSupport::Concern
-
-
1
included do
-
1
belongs_to :role, class_name: "BxBlockRolesPermissions::Role", required: false
-
1
has_many :account_groups, class_name: "BxBlockAccountGroups::AccountGroup"
-
1
has_many :groups, through: :account_groups,
-
foreign_key: "account_groups_group_id"
-
-
1
def is_groups_admin?
-
role.present? && role.name == BxBlockAccountGroups::Group::ROLE_ADMIN
-
end
-
end
-
end
-
end
-
1
module BxBlockAnnotations
-
1
module PatchAccountAnnotationsAssociation
-
1
extend ActiveSupport::Concern
-
-
1
included do
-
1
has_many :annotations, class_name: 'BxBlockAnnotations::Annotation', foreign_key: 'account_id'
-
end
-
end
-
end
-
1
module BxBlockAttachment
-
1
module PatchAccountBlockAssociations
-
1
extend ActiveSupport::Concern
-
-
1
included do
-
1
has_many :attachments, class_name: 'BxBlockAttachment::Attachment', dependent: :destroy
-
1
has_many :file_attachments, class_name: 'BxBlockAttachment::FileAttachment', dependent: :destroy
-
end
-
-
end
-
end
-
# frozen_string_literal: true
-
-
1
module BxBlockBulkUploading
-
1
module PatchAccountBlockAssociations
-
1
extend ActiveSupport::Concern
-
-
1
included do
-
1
has_many :attachments, class_name: "BxBlockAttachment::Attachment", dependent: :destroy
-
end
-
end
-
end
-
module BxBlockContentManagement
-
module Contentable
-
extend ActiveSupport::Concern
-
-
included do
-
has_one :contentable, as: :contentable, dependent: :destroy, inverse_of: :contentable,
-
class_name: "BxBlockContentManagement::Content"
-
end
-
end
-
end
-
1
module BxBlockContentManagement
-
1
module PatchAccountBlockAssociations
-
1
extend ActiveSupport::Concern
-
-
1
included do
-
1
has_many :contents_languages, class_name: "BxBlockLanguageOptions::ContentLanguage",
-
join_table: "contents_languages", dependent: :destroy
-
1
has_many :languages, -> { content_languages }, class_name: "BxBlockLanguageOptions::Language",
-
through: :contents_languages, join_table: "contents_languages"
-
1
has_many :user_sub_categories, class_name: "BxBlockCategories::UserSubCategory",
-
join_table: "user_sub_categoeries", dependent: :destroy
-
1
has_many :sub_categories, class_name: "BxBlockCategories::SubCategory", through: :user_sub_categories,
-
join_table: "user_sub_categoeries", foreign_key: :foreign_key
-
1
has_many :user_categories, class_name: "BxBlockCategories::UserCategory",
-
join_table: "user_categoeries", dependent: :destroy
-
1
has_many :categories, class_name: "BxBlockCategories::Category", through: :user_categories,
-
join_table: "user_categoeries", foreign_key: :foreign_key
-
1
has_many :bookmarks, class_name: "BxBlockContentManagement::Bookmark", dependent: :destroy
-
1
has_many :content_followings, class_name: "BxBlockContentManagement::Content",
-
through: :bookmarks, source: :content
-
1
has_many :followers, class_name: "BxBlockContentManagement::Follow", dependent: :destroy
-
end
-
-
end
-
end
-
1
module BxBlockDatastorage
-
1
module PatchAccountDatastorageAssociation
-
1
extend ActiveSupport::Concern
-
-
1
included do
-
1
has_many :file_documents, class_name: "BxBlockDatastorage::FileDocument", dependent: :destroy
-
end
-
end
-
end
-
1
module BxBlockLanguageOptions
-
1
module PatchAccountBlockAssociations
-
1
extend ActiveSupport::Concern
-
-
1
included do
-
1
belongs_to :app_language, -> { app_languages },
-
class_name: 'BxBlockLanguageOptions::Language',
-
foreign_key: :app_language_id, optional: true
-
1
has_many :contents_languages,
-
class_name: 'BxBlockLanguageOptions::ContentLanguage',
-
join_table: 'contents_languages', dependent: :destroy
-
1
has_many :languages, -> { content_languages },
-
class_name: 'BxBlockLanguageOptions::Language',
-
through: :contents_languages, join_table: 'contents_languages'
-
end
-
-
end
-
end
-
1
module BxBlockLike
-
1
module PatchAccountBlockAssociations
-
1
extend ActiveSupport::Concern
-
-
1
included do
-
1
has_many :push_notifications,
-
foreign_key: :push_notificable_id,
-
class_name: "BxBlockPushNotifications::PushNotification",
-
dependent: :destroy
-
end
-
end
-
end
-
module BxBlockLike
-
module PatchBxBlockPostsAssociations
-
extend ActiveSupport::Concern
-
-
included do
-
belongs_to :account, class_name: "AccountBlock::Account"
-
has_many :likes, as: :likeable,
-
dependent: :destroy,
-
class_name: "BxBlockLike::Like"
-
-
has_many :push_notifications,
-
foreign_key: :push_notificable_id,
-
class_name: "BxBlockPushNotifications::PushNotification",
-
dependent: :destroy
-
end
-
end
-
end
-
1
module BxBlockPayments
-
1
module PatchAccountTransactionsAssociations
-
1
extend ActiveSupport::Concern
-
-
1
included do
-
1
has_many :transactions, class_name: "BxBlockPayments::Transaction", dependent: :destroy
-
end
-
end
-
end
-
1
module BxBlockPosts
-
1
module PatchAccountBlockAssociations
-
1
extend ActiveSupport::Concern
-
-
1
included do
-
1
has_many :posts, class_name: 'BxBlockPosts::Post', dependent: :destroy
-
1
has_many_attached :images
-
end
-
-
end
-
end
-
module BxBlockProfile
-
module PatchAccountBlock
-
extend ActiveSupport::Concern
-
-
included do
-
has_many :profiles, class_name: "BxBlockProfile::Profile"
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
# rubocop:disable Style/GlobalVars
-
1
module BxBlockProfileBio
-
# patch account block
-
1
module PatchAccountBlock
-
1
extend ActiveSupport::Concern
-
-
1
included do
-
1
attr_accessor :distance_away, :is_favourite, :is_liked
-
-
1
enum gender: %i[Male Female Trans-gender], _prefix: :gender
-
-
1
has_one :profile_bio, class_name: 'BxBlockProfileBio::ProfileBio', dependent: :destroy
-
1
has_one :location, as: :locationable, class_name: 'BxBlockLocation::Location', dependent: :destroy
-
1
has_and_belongs_to_many :categories, join_table: :account_categories, class_name: 'BxBlockCategories::Category'
-
1
has_one :preference, class_name: 'BxBlockProfileBio::Preference', dependent: :destroy
-
-
1
def online?
-
$redis_onlines.exists?(id)
-
end
-
end
-
end
-
end
-
# rubocop:enable Style/GlobalVars
-
# frozen_string_literal: true
-
-
1
module BxBlockProfileBio
-
1
module PatchLocationBlock
-
1
extend ActiveSupport::Concern
-
-
1
included do
-
1
belongs_to :locationable, polymorphic: true
-
end
-
end
-
end
-
1
module BxBlockPushNotifications
-
1
module PatchAccountBlockAssociations
-
1
extend ActiveSupport::Concern
-
-
1
included do
-
1
has_many :push_notifications,
-
foreign_key: :push_notificable_id,
-
class_name: 'BxBlockPushNotifications::PushNotification',
-
dependent: :destroy
-
-
1
has_and_belongs_to_many :categories,
-
join_table: :account_categories,
-
class_name: 'BxBlockCategories::Category'
-
-
1
has_many_attached :images
-
end
-
end
-
end
-
module BxBlockRolesPermissions
-
module PatchAccountAssociations
-
extend ActiveSupport::Concern
-
included do
-
belongs_to :role, class_name: "BxBlockRolesPermissions::Role", required: false
-
end
-
end
-
end
-
1
module BxBlockShoppingCart
-
1
module PatchAccountBlock
-
1
extend ActiveSupport::Concern
-
-
1
included do
-
1
has_many :orders, class_name: "BxBlockShoppingCart::Order", foreign_key: "customer_id", dependent: :destroy
-
1
has_many_attached :images
-
end
-
end
-
end
-
1
module BxBlockTermsAndConditions
-
1
module PatchAccountBlockAssociations
-
1
extend ActiveSupport::Concern
-
-
1
included do
-
1
has_many :terms_and_conditions, class_name: "BxBlockTermsAndConditions::TermsAndCondition", dependent: :destroy
-
1
has_many :user_terms_and_conditions,
-
class_name: "BxBlockTermsAndConditions::UserTermAndCondition",
-
dependent: :destroy, foreign_key: :terms_and_condition_id
-
end
-
end
-
end
-
module AccountBlock
-
module Accounts
-
class CountryCodeAndFlagsController < ApplicationController
-
def show
-
render json: CountryCodeAndFlagSerializer
-
.new(Country.all.sort_by { |c| c.name })
-
.serializable_hash
-
end
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
module AccountBlock
-
module Accounts
-
class EmailConfirmationsController < ApplicationController
-
include BuilderJsonWebToken::JsonWebTokenValidation
-
-
before_action :validate_json_web_token
-
-
def show
-
begin
-
@account = EmailAccount.find(@token.id)
-
rescue ActiveRecord::RecordNotFound => e
-
return render json: {errors: [
-
{account: "Account Not Found"}
-
]}, status: :unprocessable_entity
-
end
-
-
if @account.activated?
-
return render json: ValidateAvailableSerializer.new(@account, meta: {
-
message: "Account Already Activated"
-
}).serializable_hash, status: :ok
-
end
-
-
@account.update activated: true
-
-
render json: ValidateAvailableSerializer.new(@account, meta: {
-
message: "Account Activated Successfully"
-
}).serializable_hash, status: :ok
-
end
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
module AccountBlock
-
module Accounts
-
class SendOtpsController < ApplicationController
-
def create
-
json_params = jsonapi_deserialize(params)
-
account = SmsAccount.find_by(
-
full_phone_number: json_params["full_phone_number"],
-
activated: true
-
)
-
-
unless account.nil?
-
return render json: {errors: [{
-
account: "Account already activated"
-
}]}, status: :unprocessable_entity
-
end
-
-
@sms_otp = SmsOtp.new(jsonapi_deserialize(params))
-
if @sms_otp.save
-
render json: SmsOtpSerializer.new(@sms_otp, meta: {
-
token: BuilderJsonWebToken.encode(@sms_otp.id)
-
}).serializable_hash, status: :created
-
else
-
render json: {errors: format_activerecord_errors(@sms_otp.errors)},
-
status: :unprocessable_entity
-
end
-
end
-
-
private
-
-
def format_activerecord_errors(errors)
-
result = []
-
errors.each do |attribute, error|
-
result << {attribute => error}
-
end
-
result
-
end
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
module AccountBlock
-
module Accounts
-
class SmsConfirmationsController < ApplicationController
-
include BuilderJsonWebToken::JsonWebTokenValidation
-
-
before_action :validate_json_web_token
-
-
def create
-
begin
-
@sms_otp = SmsOtp.find(@token.id)
-
rescue ActiveRecord::RecordNotFound => e
-
return render json: {errors: [
-
{phone: "Phone Number Not Found"}
-
]}, status: :unprocessable_entity
-
end
-
-
if @sms_otp.valid_until < Time.current
-
@sms_otp.destroy
-
-
return render json: {errors: [
-
{pin: "This Pin has expired, please request a new pin code."}
-
]}, status: :unauthorized
-
end
-
-
if @sms_otp.activated?
-
return render json: ValidateAvailableSerializer.new(@sms_otp, meta: {
-
message: "Phone Number Already Activated"
-
}).serializable_hash, status: :ok
-
end
-
-
if @sms_otp.pin.to_s == params["pin"].to_s
-
@sms_otp.activated = true
-
@sms_otp.save
-
-
render json: ValidateAvailableSerializer.new(@sms_otp, meta: {
-
message: "Phone Number Confirmed Successfully",
-
token: BuilderJsonWebToken.encode(@sms_otp.id)
-
}).serializable_hash, status: :ok
-
else
-
render json: {errors: [
-
{pin: "Invalid Pin for Phone Number"}
-
]}, status: :unprocessable_entity
-
end
-
end
-
end
-
end
-
end
-
1
module AccountBlock
-
1
class AccountsController < ApplicationController
-
1
include BuilderJsonWebToken::JsonWebTokenValidation
-
-
1
before_action :validate_json_web_token, only: [:deactivate,:search, :change_email_address, :change_phone_number, :specific_account, :logged_user]
-
-
1
SCHOOL_NAME_INVALID = "School name is invalid"
-
1
CONTACT_NUMBER_INVALID = "Contact Number is invalid"
-
1
ALREADY_REGISTRED = "Already registred"
-
-
1
def create
-
# case params[:data][:type] #### rescue invalid API format
-
# when "Student"
-
# validate_json_web_token
-
-
# unless valid_token?
-
# return render json: {errors: [
-
# {token: "Invalid Token"}
-
# ]}, status: :bad_request
-
# end
-
-
# begin
-
# # @sms_otp = SmsOtp.find(@token[:id])
-
# @school = BxBlockCategories.where(name: params[:data][:school_name]).last
-
# @student = AccountBlock::Account.where(guardian_email: params[:guardian_email], student_unique_id: params[:data][:student_id], school_id: @school.id)
-
# rescue ActiveRecord::RecordNotFound => e
-
# return render json: {errors: [
-
# {phone: "Please provide valid details"}
-
# ]}, status: :unprocessable_entity
-
# end
-
-
# when "Teacher"
-
# # account_params = jsonapi_deserialize(params)
-
# @school = BxBlockCategories.where(name: params[:data][:school_name]).last
-
# @teacher = AccountBlock::Account.where(teacher_unique_id: params[:data][:teacher_id], full_phone_number: params[:data][:contact_number], school_id: @school.id).first
-
-
# when "School Admin"
-
# @account = SocialAccount.new(jsonapi_deserialize(params))
-
# @account.password = @account.email
-
# if @account.save
-
# render json: SocialAccountSerializer.new(@account, meta: {
-
# token: encode(@account.id)
-
# }).serializable_hash, status: :created
-
# else
-
# render json: {errors: format_activerecord_errors(@account.errors)},
-
# status: :unprocessable_entity
-
# end
-
-
# else
-
# render json: {errors: [
-
# {account: "Invalid Account Type"}
-
# ]}, status: :unprocessable_entity
-
# end
-
2
account = AccountBlock::Account.find(params[:id])
-
2
if update_params[:pin] != params[:data][:confirm_pin]
-
1
return render json: {message: "confirm pin is wrong"}
-
end
-
1
if account.activated == true
-
return render json: {errors: ALREADY_REGISTRED}
-
end
-
1
updated_account = account.update(pin: update_params[:pin], activated: true) if update_params[:pin].present?
-
-
1
if updated_account
-
1
token, refresh = generate_tokens(account.id)
-
1
return render json: AccountBlock::AccountSerializer.new( account, meta: {
-
token: token, refresh_token: refresh}).as_json.merge({step: 4})
-
else
-
render json: account.errors, status: :unprocessable_entity
-
end
-
end
-
-
1
def update
-
1
account = AccountBlock::Account.find_by(id: params[:id])
-
1
account.update(update_params)
-
1
return render json: AccountBlock::AccountSerializer.new(account).as_json.merge({step: 2})
-
end
-
-
1
def show
-
1
account = AccountBlock::Account.find_by(id: params[:id])
-
1
return render json: AccountBlock::AccountSerializer.new(account).as_json.merge({step: 1})
-
end
-
-
1
def user_data
-
17
case params[:type]
-
when "Student"
-
4
for_student
-
when "Teacher"
-
4
for_teacher
-
when "School Admin"
-
4
for_school_admin
-
when "Publisher"
-
4
for_publisher
-
else
-
1
render json: {errors: [
-
{account: "Invalid User Type"}
-
]}, status: :unprocessable_entity
-
end
-
end
-
-
1
def for_student
-
4
@student = AccountBlock::Account.where(student_unique_id: params[:data][:unique_id]).last
-
4
if @student.present?
-
3
(@student.activated && @student.pin.present?) ? (render json: { errors: ALREADY_REGISTRED }) : student_errors
-
else
-
1
render json: { errors: "Please provide valid student id" }
-
end
-
end
-
1
def for_teacher
-
4
@teacher = AccountBlock::Account.where(teacher_unique_id: params[:data][:unique_id], school_id: params[:data][:school_id]).last
-
4
if @teacher.nil?
-
2
render json: { errors: "Please provide valid unique_id" }
-
2
elsif @teacher.activated && @teacher.pin.present?
-
render json: { errors: ALREADY_REGISTRED }
-
2
elsif params[:data][:contact_number] != @teacher.full_phone_number
-
1
render json: { errors: CONTACT_NUMBER_INVALID }
-
else
-
1
render json: AccountBlock::AccountSerializer.new(@teacher).as_json.merge({ step: 1 })
-
end
-
end
-
1
def for_school_admin
-
4
@school_admin = AccountBlock::Account.where(email: params[:data][:email].downcase).last
-
4
if @school_admin.present?
-
3
condition = @school_admin.activated && @school_admin.pin.present?
-
3
condition ? render(json: { errors: "ALREADY_REGISTERED" }) : school_admin_errors
-
else
-
1
return render json: {errors: "Please provide valid email"}
-
end
-
end
-
-
1
def for_publisher
-
4
@publisher = AccountBlock::Account.where(email: params[:data][:email].downcase).last
-
4
if @publisher.present?
-
3
condition = @publisher.activated && @publisher.pin.present?
-
3
condition ? render(json: { errors: ALREADY_REGISTRED }) : publisher_errors
-
else
-
1
return render json: {errors: "Account is not exist"}
-
end
-
end
-
-
1
def student_errors
-
3
if params[:data][:school_id].to_i != @student.school_id
-
1
return render json: {errors: SCHOOL_NAME_INVALID}
-
end
-
2
if params[:data][:email].present? && @student.guardian_email&.downcase != params[:data][:email].downcase
-
1
return render json: {errors: "Guardian Email is invalid"}
-
end
-
1
return render json: AccountBlock::AccountSerializer.new(@student).as_json.merge({step: 1})
-
end
-
-
1
def publisher_errors
-
3
if params[:data][:publication_name].downcase != @publisher.publication_house_name.downcase
-
1
return render json: {errors: "Publication name is invalid"}
-
end
-
2
if params[:data][:contact_number] != @publisher.full_phone_number
-
1
return render json: {errors: CONTACT_NUMBER_INVALID}
-
end
-
1
return render json: AccountBlock::AccountSerializer.new(@publisher).as_json.merge({step: 1})
-
end
-
-
-
1
def school_admin_errors
-
3
if params[:data][:school_id].to_i != @school_admin.school_id
-
1
return render json: {errors: SCHOOL_NAME_INVALID}
-
end
-
2
if params[:data][:contact_number] != @school_admin.full_phone_number
-
1
return render json: {errors: CONTACT_NUMBER_INVALID}
-
end
-
1
return render json: AccountBlock::AccountSerializer.new(@school_admin).as_json.merge({step: 1})
-
end
-
-
1
def validate_unique_id
-
7
case params[:data][:type]
-
when "Student"
-
2
@st = AccountBlock::Account.where(student_unique_id: params[:data][:unique_id]).last
-
when "Publisher"
-
1
@st = AccountBlock::Account.where(email: params[:data][:email].downcase).last
-
when "School Admin"
-
1
@st = AccountBlock::Account.where(email: params[:data][:email].downcase).last
-
when "Teacher"
-
2
@st = AccountBlock::Account.where(teacher_unique_id: params[:data][:unique_id], school_id: params[:data][:school_id]).last
-
else
-
1
return render json: {errors: [
-
{account: "Please Provide valid details"}
-
]}, status: :unprocessable_entity
-
end
-
-
6
if @st.present?
-
3
return render json: AccountBlock::AccountSerializer.new(@st), status: :ok
-
else
-
3
return render json: {errors: "Please provide valid details"}
-
end
-
end
-
-
# def search
-
# @accounts = Account.where(activated: true)
-
# .where("first_name ILIKE :search OR " \
-
# "last_name ILIKE :search OR " \
-
# "email ILIKE :search", search: "%#{search_params[:query]}%")
-
# if @accounts.present?
-
# render json: AccountSerializer.new(@accounts, meta: {message: "List of users."}).serializable_hash, status: :ok
-
# else
-
# render json: {errors: [{message: "Not found any user."}]}, status: :ok
-
# end
-
# end
-
-
# def change_email_address
-
# query_email = params["email"]
-
# account = EmailAccount.where("LOWER(email) = ?", query_email).first
-
-
# validator = EmailValidation.new(query_email)
-
-
# if account || !validator.valid?
-
# return render json: {errors: "Email invalid"}, status: :unprocessable_entity
-
# end
-
# @account = Account.find(@token.id)
-
# if @account.update(email: query_email)
-
# render json: AccountSerializer.new(@account).serializable_hash, status: :ok
-
# else
-
# render json: {errors: "account user email id is not updated"}, status: :ok
-
# end
-
# end
-
-
# def change_phone_number
-
# @account = Account.find(@token.id)
-
# if @account.update(full_phone_number: params["full_phone_number"])
-
# render json: AccountSerializer.new(@account).serializable_hash, status: :ok
-
# else
-
# render json: {errors: "account user phone_number is not updated"}, status: :ok
-
# end
-
# end
-
-
# def specific_account
-
# @account = Account.find(@token.id)
-
# if @account.present?
-
# render json: AccountSerializer.new(@account).serializable_hash, status: :ok
-
# else
-
# render json: {errors: "account does not exist"}, status: :ok
-
# end
-
# end
-
-
# def index
-
# @accounts = Account.all
-
# if @accounts.present?
-
# render json: AccountSerializer.new(@accounts).serializable_hash, status: :ok
-
# else
-
# render json: {errors: "accounts data does not exist"}, status: :ok
-
# end
-
# end
-
-
# def logged_user
-
# @account = Account.find(@token.id)
-
# if @account.present?
-
# render json: AccountSerializer.new(@account).serializable_hash, status: :ok
-
# else
-
# render json: {errors: "account does not exist"}, status: :ok
-
# end
-
# end
-
-
1
def deactivate
-
2
account = AccountBlock::Account.find(@token.id)
-
2
if account.activated
-
1
account.update(activated: false)
-
1
render json: { message: "Your account has been deactivated." }
-
else
-
1
render json: { errors: ["Your account is already deactivated."] }, status: :unprocessable_entity
-
end
-
end
-
-
-
# private
-
-
1
def generate_tokens(account_id)
-
[
-
1
BuilderJsonWebToken.encode(account_id, 1.day.from_now, token_type: 'sign_up'),
-
BuilderJsonWebToken.encode(account_id, 1.year.from_now, token_type: 'refresh')
-
]
-
end
-
-
# def search_params
-
# params.permit(:query)
-
# end
-
-
1
def update_params
-
5
params.require(:data).permit(:ifsc_code, :bank_account_number, :publication_house_name, :guardian_name, :first_name, :guardian_contact_no, :pin, :role_id, :full_phone_number)
-
end
-
end
-
end
-
1
module AccountBlock
-
1
class ApplicationController < BuilderBase::ApplicationController
-
# protect_from_forgery with: :exception
-
end
-
end
-
1
class ApplicationController < ActionController::Base
-
336
protect_from_forgery unless: -> { request.format.json? }
-
end
-
1
module BuilderBase
-
1
class ApplicationController < ::ApplicationController
-
1
include JSONAPI::Deserialization
-
1
rescue_from ActiveRecord::RecordNotFound, :with => :not_found
-
-
1
def not_found
-
1
render :json => {'errors' => ['Record not found']}, :status => :not_found
-
end
-
end
-
end
-
module BxBlockAccountGroups
-
class ApplicationController < BuilderBase::ApplicationController
-
include BuilderJsonWebToken::JsonWebTokenValidation
-
-
before_action :validate_json_web_token
-
-
rescue_from ActiveRecord::RecordNotFound, with: :not_found
-
-
private
-
-
def not_found
-
render json: {"errors" => ["Record not found"]}, status: :not_found
-
end
-
-
def current_user
-
@current_user ||= AccountBlock::Account.find(@token.id)
-
rescue ActiveRecord::RecordNotFound
-
render json: {
-
errors: [{message: "Authentication token invalid"}]
-
}, status: :unprocessable_entity
-
end
-
end
-
end
-
module BxBlockAccountGroups
-
class GroupsController < ApplicationController
-
before_action :check_account_role
-
before_action :check_is_admin, only: [:create, :update, :add_accounts, :remove_accounts, :destroy]
-
before_action :find_group, only: [:show, :update, :add_accounts, :remove_accounts, :destroy]
-
-
def index
-
render json: GroupSerializer.new(my_groups), status: :ok
-
end
-
-
def show
-
if @group.blank?
-
render json: {errors: [{group: "Not found"}]}, status: :not_found
-
else
-
render json: GroupSerializer.new(@group).serializable_hash, status: :ok
-
end
-
end
-
-
def create
-
group = Group.new(group_create_params)
-
unless group.save
-
render json: {errors: group.errors}, status: :unprocessable_entity
-
end
-
-
if params[:group]["account_ids"].present?
-
accounts = AccountBlock::Account.where(id: params[:group]["account_ids"])
-
group.accounts = accounts if accounts&.present?
-
end
-
-
if group.save
-
render json: GroupSerializer.new(group).serializable_hash, status: :created
-
end
-
end
-
-
def update
-
if @group.update(group_update_params)
-
render json: GroupSerializer.new(@group).serializable_hash, status: :ok
-
else
-
render json: {errors: @group.errors}, status: :unprocessable_entity
-
end
-
end
-
-
def add_accounts
-
if params[:account_ids].blank?
-
render json: {
-
errors: [{message: "No account ids provided"}]
-
}, status: :unprocessable_entity and return
-
end
-
-
accounts_to_add = AccountBlock::Account.where(id: params[:account_ids]).where.not(id: @group.accounts.map(&:id))
-
@group.accounts << accounts_to_add
-
render json: GroupSerializer.new(@group).serializable_hash, status: :ok
-
end
-
-
def remove_accounts
-
if params[:account_ids].blank?
-
render json: {
-
errors: [{message: "No account ids provided"}]
-
}, status: :unprocessable_entity and return
-
end
-
-
accounts_to_remove = AccountBlock::Account.where(id: params[:account_ids])
-
@group.accounts = @group.accounts.excluding(accounts_to_remove)
-
render json: GroupSerializer.new(@group).serializable_hash, status: :ok
-
end
-
-
def destroy
-
if @group.destroy
-
render json: {message: "Group deleted successfully!"}, status: :ok
-
else
-
render json: GroupSerializer.new(@group).serializable_hash, status: :unprocessable_entity
-
end
-
end
-
-
private
-
-
def group_create_params
-
params.require(:group).permit(:name, :settings, settings: {})
-
end
-
-
def group_update_params
-
params.require(:group).permit(:name, :settings, settings: {}, account_ids: [])
-
end
-
-
def check_account_role
-
unless current_user.role.present? && [Group::ROLE_ADMIN, Group::ROLE_BASIC].include?(current_user.role.name)
-
render json: {
-
errors: [{message: "Account does not have a proper role"}]
-
}, status: :unprocessable_entity
-
end
-
end
-
-
def check_is_admin
-
unless current_user.is_groups_admin?
-
render json: {
-
errors: [{message: "Only account group admin has permission for this"}]
-
}, status: :unprocessable_entity
-
end
-
end
-
-
def find_group
-
unless current_user.is_groups_admin?
-
if current_user.groups.empty? || !current_user.groups.any? { |group| group.id == params[:id].to_i }
-
return render json: {
-
errors: [{message: "You don't have access to this account group"}]
-
}, status: :unprocessable_entity
-
end
-
end
-
-
@group ||= Group.find_by_id(params[:id])
-
-
unless @group.present?
-
render json: {
-
errors: [{message: "Group not found"}]
-
}, status: :not_found
-
end
-
end
-
-
def my_groups
-
current_user.is_groups_admin? ? Group.all : current_user.groups
-
end
-
end
-
end
-
module BxBlockAddress
-
class AddressesController < BxBlockAddress::ApplicationController
-
before_action :get_account, only: [:index, :create, :update, :destroy]
-
before_action :find_address, only: [:update, :destroy]
-
before_action :validate_address_type, only: [:create, :update]
-
-
def index
-
@account_addresses = Address.where(addressble_id: @account.id)
-
unless @account_addresses.present?
-
render json: {
-
message: "No Address is present"
-
} and return
-
end
-
render json: BxBlockAddress::AddressSerializer.new(
-
@account_addresses, meta: {message: "List of all addresses"}
-
).serializable_hash
-
end
-
-
def create
-
@address = Address.new(full_params)
-
if @address.save
-
render json: BxBlockAddress::AddressSerializer.new(@address, meta: {
-
message: "Address Created Successfully"
-
}).serializable_hash, status: :created
-
else
-
render json: {errors: format_activerecord_errors(@address.errors)},
-
status: :unprocessable_entity
-
end
-
end
-
-
def update
-
if @address.update(full_params)
-
render json: BxBlockAddress::AddressSerializer.new(@address, meta: {
-
message: "Address Updated Successfully"
-
}).serializable_hash, status: :ok
-
else
-
render json: {errors: format_activerecord_errors(@address.errors)},
-
status: :unprocessable_entity
-
end
-
end
-
-
def destroy
-
if @address.destroy
-
render json: {message: "Address deleted succesfully!"}, status: :ok
-
else
-
render json: {errors: format_activerecord_errors(@address.errors)},
-
status: :unprocessable_entity
-
end
-
end
-
-
private
-
-
def address_params
-
params.require(:address).permit(:latitude, :longitude, :address, :address_type)
-
end
-
-
def full_params
-
@full_params ||= address_params.merge({addressble_id: @account.id,
-
addressble_type: "AccountBlock::Account"})
-
end
-
-
def find_address
-
@address = Address.find_by(addressble_id: @account.id, id: params[:id])
-
return render json: {message: "Address does not exist."}, status: :not_found if @address.nil?
-
end
-
-
def validate_address_type
-
if full_params[:address_type].present? && !BxBlockAddress::Address.address_types.key?(full_params[:address_type])
-
render json: {message: "Address type is not valid."}, status: :unprocessable_entity and return
-
end
-
end
-
end
-
end
-
module BxBlockAddress
-
class ApplicationController < BuilderBase::ApplicationController
-
include BuilderJsonWebToken::JsonWebTokenValidation
-
-
before_action :validate_json_web_token
-
-
rescue_from ActiveRecord::RecordNotFound, with: :not_found
-
-
private
-
-
def not_found
-
render json: {"errors" => ["Record not found"]}, status: :not_found
-
end
-
-
def get_account
-
@account = AccountBlock::Account.find(@token.id)
-
end
-
-
def format_activerecord_errors(errors)
-
result = []
-
errors.each do |attribute, error|
-
result << {attribute => error}
-
end
-
result
-
end
-
end
-
end
-
module BxBlockAdmin
-
class ApplicationController < BuilderBase::ApplicationController
-
# protect_from_forgery with: :exception
-
end
-
end
-
1
module BxBlockAnalytics7
-
1
class ApplicationController < BuilderBase::ApplicationController
-
1
include BuilderJsonWebToken::JsonWebTokenValidation
-
-
1
before_action :validate_json_web_token
-
-
1
rescue_from ActiveRecord::RecordNotFound, :with => :not_found
-
-
1
private
-
-
1
def not_found
-
render :json => {'errors' => ['Record not found']}, :status => :not_found
-
end
-
end
-
end
-
1
module BxBlockAnalytics7
-
1
class PublisherAnalyticsController < ApplicationController
-
1
before_action :validate_json_web_token, :current_user
-
-
1
def publisher_analytics
-
2
if current_user.present?
-
2
if current_user.role.name == "Publisher"
-
1
@all_teachers = count_users_by_role("Teacher")
-
1
@all_school_admin = count_users_by_role("School Admin")
-
1
@all_students = count_users_by_role("Student")
-
1
@all_publishers = count_users_by_role("Publisher")
-
1
@all_ebooks = BxBlockBulkUploading::Ebook.all.count
-
1
@all_users = @all_teachers + @all_school_admin + @all_students
-
1
@last_week_change = calculate_last_week_change
-
1
@total_ebooks_sold = 0
-
1
@last_week_ebooks = 0
-
1
@total_revenue = 0
-
1
@last_week_revenue = 0
-
1
users_data = { total_users: @all_users, last_week: @last_week_change }
-
1
ebooks_data = { total_ebooks_sold: @total_ebooks_sold, last_week_ebooks: @last_week_ebooks }
-
1
revenue_generated = { total_revenue: @total_revenue, last_week_revenue: @last_week_revenue }
-
1
render json: { users_data: users_data, ebooks_data: ebooks_data, revenue_generated: revenue_generated, success: true }, status: :ok
-
else
-
1
render json: { message: "Invalid User!" }, status: :unprocessable_entity
-
end
-
else
-
render json: { message: "User Not Found!" }, status: :not_found
-
end
-
end
-
-
1
private
-
-
1
def current_user
-
6
@account = AccountBlock::Account.find_by(id: @token.id)
-
end
-
-
1
def count_users_by_role(role_name)
-
4
AccountBlock::Account.joins(:role).where(roles: { name: role_name }).size
-
end
-
-
1
def calculate_last_week_change
-
1
last_week_teachers = count_users_by_role_created_last_week("Teacher")
-
1
last_week_school_admin = count_users_by_role_created_last_week("School Admin")
-
1
last_week_students = count_users_by_role_created_last_week("Student")
-
# last_week_publishers = count_users_by_role_created_last_week("Publisher")
-
-
1
last_week_teachers + last_week_school_admin + last_week_students
-
end
-
-
1
def count_users_by_role_created_last_week(role_name)
-
3
AccountBlock::Account.joins(:role)
-
.where(roles: { name: role_name })
-
.where(created_at: 1.week.ago..Time.now)
-
.size
-
end
-
end
-
end
-
1
module BxBlockAnalytics7
-
1
class SchoolAdminAnalyticsController < ApplicationController
-
1
before_action :validate_json_web_token, :current_user
-
-
1
def get_all_data
-
2
if current_user.present?
-
2
if current_user.role.name == "School Admin"
-
1
@school = current_user.school
-
1
@all_teachers = AccountBlock::Account.where(role_id: BxBlockRolesPermissions::Role.find_by(name: "Teacher"), school_id: @school.id).count
-
1
@all_students = AccountBlock::Account.where(role_id: BxBlockRolesPermissions::Role.find_by(name: "Student"), school_id: @school.id).count
-
1
@all_publishers = AccountBlock::Account.joins(:role).where(roles: {name: "Publisher"}).size
-
1
@all_ebooks = BxBlockBulkUploading::Ebook.all.count
-
1
@all_videos = 0
-
1
@all_assignments = 0
-
1
total_contents = {ebooks: @all_ebooks, videos: @all_videos, assignments: @all_assignments}
-
1
data = {students: @all_students, teachers: @all_teachers, publishers: @all_publishers}
-
1
render json: {data: data, total_contents: total_contents, success: true}, status: :ok
-
else
-
1
render json: {message: "Invalid User!"}, status: :unprocessable_entity
-
end
-
else
-
render json: {message: "User Not Found!"}, status: :not_found
-
end
-
end
-
-
1
private
-
-
1
def current_user
-
7
@account = AccountBlock::Account.find_by(id: @token.id)
-
end
-
end
-
end
-
module BxBlockAnnotations
-
class AnnotationsController < ApplicationController
-
before_action :current_user
-
before_action :get_annotation, only: [:edit, :show, :update, :destroy]
-
-
def index
-
@annotation = @account.annotations.ordered_by_id
-
response_render(@annotation)
-
end
-
-
def all_annotations
-
@annotation = BxBlockAnnotations::Annotation.all.ordered_by_id
-
response_render(@annotation)
-
end
-
-
def create
-
@annotation = BxBlockAnnotations::Annotation.new(title: params[:title], description: params[:description], account_id: @account.id)
-
if @annotation.save
-
response_render(@annotation)
-
else
-
render json: {
-
errors: format_activerecord_errors(@annotation.errors)
-
}, status: :unprocessable_entity
-
end
-
end
-
-
def edit
-
response_render(@annotation)
-
end
-
-
def show
-
response_render(@annotation)
-
end
-
-
def update
-
@annotation.update(title: params[:title], description: params[:description])
-
@annotation.save
-
response_render(@annotation)
-
end
-
-
def destroy
-
@annotation.destroy
-
render json:{meta: {message: "Annotation delete is successfully."}}
-
end
-
-
private
-
def response_render(annotation)
-
host = request.base_url
-
render json: BxBlockAnnotations::AnnotationSerializer.new(annotation, params: {account: @account, host: host}
-
).serializable_hash, except: :attachment, status: :ok
-
end
-
-
def get_annotation
-
@annotation = BxBlockAnnotations::Annotation.find params[:id]
-
end
-
-
def current_user
-
@account = AccountBlock::Account.find_by(id: @token.id)
-
end
-
end
-
end
-
module BxBlockAnnotations
-
class ApplicationController < BuilderBase::ApplicationController
-
include BuilderJsonWebToken::JsonWebTokenValidation
-
-
before_action :validate_json_web_token
-
-
rescue_from ActiveRecord::RecordNotFound, :with => :not_found
-
-
private
-
-
def not_found
-
render :json => {'errors' => ['Record not found']}, :status => :not_found
-
end
-
end
-
end
-
module BxBlockAppointmentManagement
-
class ApplicationController < BuilderBase::ApplicationController
-
include BuilderJsonWebToken::JsonWebTokenValidation
-
-
before_action :validate_json_web_token
-
end
-
end
-
module BxBlockAppointmentManagement
-
class AvailabilitiesController < ApplicationController
-
before_action :set_current_user, only: [:create, :destroy]
-
before_action :check_service_provider, only: [:index, :destroy]
-
-
def index
-
if params[:availability_date].blank?
-
render json: {errors: [
-
{availability: "Date is an empty."}
-
]}, status: :unprocessable_entity
-
else
-
availability = Availability.find_by(
-
availability_date: Date.parse(params[:availability_date]).strftime("%d/%m/%Y")
-
)
-
unless availability.present?
-
render json: {
-
message: "No slots present for date " \
-
"#{Date.parse(params[:availability_date]).strftime("%d/%m/%Y")}"
-
} and return
-
end
-
render json: ServiceProviderAvailabilitySerializer.new(
-
availability, meta: {message: "List of all slots"}
-
)
-
end
-
end
-
-
def create
-
availability = Availability.new(
-
availability_params.merge(service_provider_id: @current_user.id)
-
)
-
if availability.save
-
trigger_slot_worker(availability)
-
render json: ServiceProviderAvailabilitySerializer.new(availability), status: 201
-
else
-
render json: {errors: [{slot_error: availability.errors.full_messages.first}]},
-
status: :unprocessable_entity
-
end
-
end
-
-
def destroy
-
availability = BxBlockAppointmentManagement::Availability.find_by(service_provider_id: params[:service_provider_id])
-
if availability.destroy
-
render json: {message: "Availability deleted successfully"}, status: :ok
-
else
-
render json: {message: "Availability not found"}, status: 422
-
end
-
end
-
-
def check_service_provider
-
availability = Availability.find_by(service_provider_id: params[:service_provider_id])
-
return render json: {message: "Service Provider is not found."}, status: 404 unless availability
-
end
-
-
private
-
-
def availability_params
-
params.require(:availability).permit(:start_time, :end_time, :availability_date)
-
end
-
-
def trigger_slot_worker availability
-
BxBlockAppointmentManagement::CreateAvailabilityWorker.perform_async(availability.id)
-
end
-
-
def set_current_user
-
@current_user = AccountBlock::Account.find(@token.id)
-
end
-
end
-
end
-
module BxBlockAttachment
-
class ApplicationController < BuilderBase::ApplicationController
-
# protect_from_forgery with: :exception
-
end
-
end
-
module BxBlockAttachment
-
class AttachmentsController < ApplicationController
-
include BuilderJsonWebToken::JsonWebTokenValidation
-
before_action :validate_json_web_token, :validate_blacklisted_user
-
before_action :set_account, only: [:get_user_attachments, :create]
-
before_action :set_attachment, only: [:save_print_properties, :set_is_printed]
-
-
def get_user_attachments
-
if @account.present?
-
if @account.attachments.present?
-
@attachments = Array.new
-
@account.attachments.order('created_at DESC').each do |attachment|
-
if attachment&.attachment&.attached? && attachment.orders&.blank?
-
@attachments << attachment
-
end
-
end
-
if @attachments.present?
-
render json: AttachmentSerializer.new(@attachments).serializable_hash
-
else
-
return render json: {errors: [
-
{account: 'No Attachments for this user'},
-
]}, status: :unprocessable_entity
-
end
-
else
-
return render json: {errors: [
-
{account: 'No Attachments for this user'},
-
]}, status: :unprocessable_entity
-
end
-
else
-
return render json: {errors: [
-
{account: 'User not found'},
-
]}, status: :unprocessable_entity
-
end
-
end
-
-
def save_print_properties
-
if @attachment.present?
-
if params[:attachment_data][:set_all] == "1"
-
if @attachment.account.attachments.present?
-
# document_count = 0
-
params[:attachment_data][:colour] = params[:attachment_data][:colour].capitalize
-
params[:attachment_data][:page_size] = params[:attachment_data][:page_size].capitalize
-
params[:attachment_data][:print_sides] = params[:attachment_data][:print_sides].capitalize
-
@attachment.account.attachments.each do |attachment|
-
if attachment&.attachment&.attached?
-
if attachment.update_attributes(attachments_params)
-
# document_count += 1
-
else
-
render json: {errors: @attachment.errors},
-
status: :unprocessable_entity
-
end
-
end
-
end
-
if params[:attachment_data][:total_doc].present? and params[:attachment_data][:total_doc].to_i > 0
-
document_count = params[:attachment_data][:total_doc]
-
render json: AttachmentSerializer.new(@attachment.account.attachments, meta: {
-
message: "All #{document_count} Documents Updated Successfully"
-
}).serializable_hash, status: :ok
-
end
-
end
-
else
-
params[:attachment_data][:colour] = params[:attachment_data][:colour].capitalize
-
params[:attachment_data][:page_size] = params[:attachment_data][:page_size].capitalize
-
params[:attachment_data][:print_sides] = params[:attachment_data][:print_sides].capitalize
-
if @attachment.update_attributes(attachments_params)
-
render json: AttachmentSerializer.new(@attachment, meta: {
-
message: "Document Updated Successfully"
-
}).serializable_hash, status: :ok
-
else
-
render json: {errors: @attachment.errors},
-
status: :unprocessable_entity
-
end
-
end
-
else
-
return render json: {errors: [
-
{account: 'Document not found'},
-
]}, status: :unprocessable_entity
-
end
-
end
-
-
def set_is_printed
-
if @attachment.update_attributes(is_printed: params[:data][:is_printed])
-
render json: AttachmentSerializer.new(@attachment).serializable_hash
-
else
-
return render json: {errors: [
-
{account: 'Something went wrong'},
-
]}
-
end
-
end
-
-
private
-
-
def set_attachment
-
@attachment = BxBlockAttachment::Attachment.find(params[:id])
-
end
-
-
def set_account
-
if params[:data].present?
-
@account = AccountBlock::Account.find params[:data][:account_id]
-
else
-
@account = AccountBlock::Account.find params[:id]
-
end
-
end
-
-
def attachments_params
-
params.require(:attachment_data).permit(:colour, :layout, :page_size, :scale, :print_sides,
-
:print_pages_from, :print_pages_to, :total_pages,
-
:is_expired, :attachment)
-
end
-
-
def format_activerecord_errors(errors)
-
result = []
-
errors.each do |attribute, error|
-
result << { attribute => error }
-
end
-
result
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
module BxBlockAttachment
-
class FileAttachmentsController < ApplicationController
-
include BuilderJsonWebToken::JsonWebTokenValidation
-
include ActiveStorage::SetCurrent
-
before_action :validate_json_web_token
-
-
def index
-
@file_attachments = BxBlockAttachment::FileAttachment.where(created_by: @token.id).all
-
render json: { date: FileAttachmentSerializer.new(@file_attachments).serializable_hash }, status: :ok
-
end
-
-
def create
-
@file_attachment = BxBlockAttachment::FileAttachment.new(file_attachment_params)
-
@file_attachment.created_by = @token.id
-
if @file_attachment.save
-
-
render json: { data: FileAttachmentSerializer.new(@file_attachment).serializable_hash }, status: :created
-
else
-
render json: { errors: @file_attachment.errors.full_messages }, status: :unprocessable_entity
-
end
-
end
-
-
def destroy
-
file_attachment = BxBlockAttachment::FileAttachment.find_by(id: params[:id], created_by: @token.id)
-
unless file_attachment.present?
-
return render json: {
-
errors: [
-
{ message: 'File Attachment does not exist.' }
-
]
-
}, status: :unprocessable_entity
-
end
-
if file_attachment.destroy
-
render json: { message: 'File Attachment deleted.' }, status: :ok
-
else
-
render json: BxBlockAttachment::ErrorSerializer.new(file_attachment), status: :unprocessable_entity
-
-
end
-
end
-
-
def update
-
file_attachment = BxBlockAttachment::FileAttachment.find_by(id: params[:id], created_by: @token.id)
-
-
return render json: { errors: 'File Attachment not found' }, status: :not_found if file_attachment.blank?
-
-
if file_attachment.update(file_attachment_params)
-
-
render json: { data: FileAttachmentSerializer.new(file_attachment).serializable_hash }, status: :ok
-
else
-
render json: { errors: file_attachment.errors.full_messages }, status: :bad_request
-
-
end
-
end
-
-
private
-
-
def file_attachment_params
-
params[:attachment] = params[:url]
-
params.permit(:name, :description, :embeded_code, :url, :tag, :content_type, :thumnail, :is_active,
-
:updated_by, :created_by, :attachment)
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
1
module BxBlockBulkUploading
-
1
class ApplicationController < BuilderBase::ApplicationController
-
1
include BuilderJsonWebToken::JsonWebTokenValidation
-
-
1
before_action :validate_json_web_token
-
-
1
rescue_from ActiveRecord::RecordNotFound, with: :not_found
-
-
# def current_user
-
# @current_user = AccountBlock::Account.find(@token.id)
-
# rescue ActiveRecord::RecordNotFound => e
-
# render json: {errors: [
-
# {message: "Please login again."}
-
# ]}, status: :unprocessable_entity
-
# end
-
-
1
private
-
-
1
def not_found
-
1
render json: {"errors" => ["Record not found"]}, status: :not_found
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
require "open-uri"
-
require "tmpdir"
-
require "libreconv"
-
require "aws-sdk"
-
require "aws-sdk-s3"
-
require "base64"
-
-
module BxBlockBulkUploading
-
class AttachmentsController < ApplicationController
-
include BuilderJsonWebToken::JsonWebTokenValidation
-
before_action :current_user
-
-
def index
-
attachments = Attachment.where(account_id: current_user.id)
-
attachment_output = []
-
attachments.each do |attachment|
-
attachment_output << if attachment&.status == "completed"
-
AttachmentSerializer.new(attachment, meta: {
-
message: "Attachment Created Successfully"
-
})
-
elsif attachment&.status != "failed"
-
AttachmentSerializer.new(attachment, meta: {
-
message: "Attachment in progress"
-
})
-
-
else
-
AttachmentSerializer.new(attachment, meta: {
-
message: "Some error occured"
-
})
-
end
-
end
-
render json: attachment_output, status: :ok
-
end
-
-
def create
-
attachment = Attachment.new(account_id: current_user.id, status: "processing")
-
unless attachment.save
-
render(json: {message: "Attachment not saved"}, status: :unprocessable_entity)
-
return
-
end
-
-
errors = do_upload(attachment, attachments_params[:files])
-
-
if attachment.reload.status == "completed"
-
render json: AttachmentSerializer.new(attachment, meta: {
-
message: "Attachment Created Successfully"
-
}).serializable_hash, status: :created
-
else
-
render json: {errors: errors}, status: :unprocessable_entity
-
end
-
end
-
-
def show
-
attachment = Attachment.find(params[:id])
-
if attachment&.status == "completed"
-
render json: AttachmentSerializer.new(attachment, meta: {
-
message: "Bulk upload job done"
-
}).serializable_hash, status: :ok
-
elsif attachment&.status != "failed"
-
render json: {message: "Bulk Upload In Progress"}, status: :ok
-
else
-
render json: {message: "Some error occured"}, status: :unprocessable_entity
-
end
-
end
-
-
def destroy
-
attachment = Attachment.find(params[:id])
-
unless attachment.present?
-
return render json: {message: "attachment does not exist."},
-
status: :unprocessable_entity
-
end
-
if attachment.destroy
-
render json: {message: "Deleted."}, status: :ok
-
else
-
render json: {errors: format_activerecord_errors(attachment.errors)},
-
status: :unprocessable_entity
-
end
-
end
-
-
def delete_attachment
-
attachment = Attachment.find_by(id: params[:id], account_id: current_user.id)
-
if attachment.present?
-
file = ActiveStorage::Attachment.find_by(id: params[:file_id], record_id: attachment.id)
-
unless file.present?
-
return render json: {message: "File does not exist."},
-
status: :unprocessable_entity
-
end
-
if file.destroy
-
render json: {message: "Attachment file deleted successfully."}, status: :ok
-
else
-
render json: {errors: format_activerecord_errors(file.errors)},
-
status: :unprocessable_entity
-
end
-
else
-
render json: {message: "Attachment file does not exist with this account"}, status: :unprocessable_entity
-
end
-
end
-
-
private
-
-
def attachments_params
-
params.permit(files: [])
-
end
-
-
def format_activerecord_errors(errors)
-
result = []
-
errors.each do |attribute, error|
-
result << {attribute => error}
-
end
-
result
-
end
-
-
def do_upload(attachment, files)
-
attachment.update!(files: files, status: "completed")
-
rescue
-
errors = format_activerecord_errors(attachment.errors)
-
attachment.update!(files: [], status: "failed")
-
-
errors
-
end
-
end
-
end
-
1
module BxBlockBulkUploading
-
1
class EbookAssignsController < ApplicationController
-
1
before_action :validate_json_web_token, only: [:ebook_assign]
-
-
1
def ebook_assign
-
1
book_id = params[:ebook_id]
-
1
student_ids = params[:student_ids]
-
-
1
student_ids.each do |student_id|
-
1
student = AccountBlock::Account.find(student_id)
-
1
school_class_id = student.school_class_id
-
1
class_division_id = student.class_division_id
-
1
school_id = student.school_id
-
1
BxBlockBulkUploading::EbookAllotment.create!(
-
account_id: @token.id,
-
student_id: student_id,
-
ebook_id: book_id,
-
alloted_date: Date.today,
-
school_class_id: school_class_id,
-
class_division_id: class_division_id,
-
school_id: school_id
-
)
-
end
-
1
render json: { 'message': 'Book assigned successfully' }, status: :ok
-
end
-
end
-
end
-
1
module BxBlockBulkUploading
-
1
class EbooksController < ApplicationController
-
1
before_action :validate_json_web_token, :current_user
-
-
1
def get_ebooks
-
3
@ebooks = Ebook.all.page(params[:page]).per(params[:per_page])
-
3
if @ebooks.count.positive?
-
1
render json: { message: 'Ebooks listed successfully', ebooks: EbookSerializer.new(@ebooks, serialization_options).serializable_hash, ebooks_count: @ebooks.count }, status: :ok
-
else
-
2
render json: { message: 'there is no ebooks to show', ebook_count: @ebooks.count }
-
end
-
end
-
-
1
def show
-
2
if current_user.present?
-
begin
-
2
@ebook = BxBlockBulkUploading::Ebook.find(params[:id])
-
1
render json: { message: 'Ebook Show successfully', ebooks: EbookSerializer.new(@ebook, serialization_options).serializable_hash }, status: :ok
-
1
rescue ActiveRecord::RecordNotFound
-
1
render_not_found("Ebook not found")
-
end
-
else
-
render json: { message: "User Not Found!" }, status: :not_found
-
end
-
end
-
-
1
private
-
-
1
def current_user
-
7
@account = AccountBlock::Account.find_by(id: @token.id)
-
end
-
-
1
def serialization_options
-
2
{ params: { host: request.protocol + request.host_with_port } }
-
end
-
end
-
end
-
1
module BxBlockCatalogue
-
1
class ApplicationController < BuilderBase::ApplicationController
-
1
include BuilderJsonWebToken::JsonWebTokenValidation
-
-
1
before_action :validate_json_web_token
-
-
1
rescue_from ActiveRecord::RecordNotFound, with: :not_found
-
-
1
private
-
-
1
def not_found
-
1
render json: {"errors" => ["Record not found"]}, status: :not_found
-
end
-
end
-
end
-
module BxBlockCatalogue
-
class BrandsController < ApplicationController
-
def create
-
brand = Brand.new(brand_params)
-
save_result = brand.save
-
-
if save_result
-
render json: BrandSerializer.new(brand).serializable_hash,
-
status: :created
-
else
-
render json: ErrorSerializer.new(brand).serializable_hash,
-
status: :unprocessable_entity
-
end
-
rescue ArgumentError
-
render json: { message: "Please Enter Valid Currency From List", Currencies: Brand.currencies.keys }
-
end
-
-
def index
-
serializer = BrandSerializer.new(Brand.all)
-
-
render json: serializer, status: :ok
-
end
-
-
private
-
-
def brand_params
-
params.require(:brand).permit(:name, :currency)
-
end
-
end
-
end
-
module BxBlockCatalogue
-
class CataloguesController < ApplicationController
-
before_action :load_catalogue, only: %i[show update destroy]
-
-
def create
-
catalogue = Catalogue.new(catalogue_params)
-
save_result = catalogue.save
-
-
if save_result
-
process_images(catalogue, params[:images])
-
-
catalogue.tags << Tag.where(id: params[:tags_id])
-
-
process_variants_images(catalogue)
-
-
render json: CatalogueSerializer.new(catalogue, serialization_options)
-
.serializable_hash,
-
status: :created
-
else
-
render json: ErrorSerializer.new(catalogue).serializable_hash,
-
status: :unprocessable_entity
-
end
-
end
-
-
def show
-
return if @catalogue.nil?
-
-
render json: CatalogueSerializer.new(@catalogue, serialization_options)
-
.serializable_hash,
-
status: :ok
-
end
-
-
def index
-
catalogues = Catalogue.all
-
serializer = CatalogueSerializer.new(catalogues, serialization_options)
-
-
render json: serializer, status: :ok
-
end
-
-
def destroy
-
return if @catalogue.nil?
-
-
if @catalogue.destroy
-
render json: {success: true}, status: :ok
-
else
-
render json: ErrorSerializer.new(@catalogue).serializable_hash,
-
status: :unprocessable_entity
-
end
-
end
-
-
def update
-
return if @catalogue.nil?
-
-
update_result = @catalogue.update(catalogue_params)
-
-
update_tags
-
process_images(@catalogue, params[:images])
-
process_variants_images(@catalogue)
-
-
if update_result
-
render json: CatalogueSerializer.new(@catalogue, serialization_options)
-
.serializable_hash,
-
status: :ok
-
else
-
render json: ErrorSerializer.new(@catalogue).serializable_hash,
-
status: :unprocessable_entity
-
end
-
end
-
-
private
-
-
def load_catalogue
-
@catalogue = Catalogue.find_by(id: params[:id])
-
-
if @catalogue.nil?
-
render json: {
-
message: "Catalogue with id #{params[:id]} doesn't exists"
-
}, status: :not_found
-
end
-
end
-
-
def catalogue_params
-
params.permit(:category_id, :sub_category_id, :brand_id,
-
:name, :sku, :description, :manufacture_date, :length,
-
:breadth, :height, :stock_qty, :availability, :weight,
-
:price, :recommended, :on_sale, :sale_price, :discount,
-
catalogue_variants_attributes:
-
%i[id catalogue_variant_color_id
-
catalogue_variant_size_id price stock_qty
-
on_sale sale_price discount_price length breadth
-
height _destroy])
-
end
-
-
def update_tags
-
tags = @catalogue.tags
-
-
existing_tags_id = tags.map(&:id)
-
params_tags = params[:tags_id] || []
-
-
remove_ids = existing_tags_id - params_tags
-
if remove_ids.size.positive?
-
@catalogue.tags.delete(Tag.where(id: remove_ids))
-
end
-
-
add_ids = params_tags - existing_tags_id
-
if add_ids.size.positive?
-
@catalogue.tags << Tag.where(id: add_ids)
-
end
-
end
-
-
def process_images(imagable, images_params)
-
return unless images_params.present?
-
-
images_to_attach = []
-
images_to_remove = []
-
-
images_params.each do |image_data|
-
if image_data[:id].present? &&
-
(image_data[:remove].present? || image_data[:data].present?)
-
images_to_remove << image_data[:id]
-
end
-
-
if image_data[:data]
-
images_to_attach.push(
-
io: StringIO.new(Base64.decode64(image_data[:data])),
-
content_type: image_data[:content_type],
-
filename: image_data[:filename]
-
)
-
end
-
end
-
-
imagable.images.where(id: images_to_remove).purge if
-
images_to_remove.size.positive?
-
imagable.images.attach(images_to_attach) if
-
images_to_attach.size.positive?
-
end
-
-
def process_variants_images(catalogue)
-
variants = params[:catalogue_variants_attributes]
-
-
return unless variants.present?
-
-
variants.each_with_index do |v, index|
-
next unless v[:images].present?
-
-
process_images(catalogue.catalogue_variants[index], v[:images])
-
end
-
end
-
-
def serialization_options
-
{params: {host: request.protocol + request.host_with_port}}
-
end
-
end
-
end
-
module BxBlockCatalogue
-
class CataloguesVariantsColorsController < ApplicationController
-
def create
-
colors = CatalogueVariantColor.new(name: params[:name])
-
save_result = colors.save
-
-
if save_result
-
render json: CatalogueVariantColorSerializer.new(colors)
-
.serializable_hash,
-
status: :created
-
else
-
render json: ErrorSerializer.new(colors).serializable_hash,
-
status: :unprocessable_entity
-
end
-
end
-
-
def index
-
serializer = CatalogueVariantColorSerializer.new(
-
CatalogueVariantColor.all
-
)
-
-
render json: serializer, status: :ok
-
end
-
end
-
end
-
module BxBlockCatalogue
-
class CataloguesVariantsController < ApplicationController
-
def create
-
variant = CatalogueVariant.new(variants_params)
-
save_result = variant.save
-
-
if save_result
-
render json: CatalogueVariantSerializer.new(
-
variant, serialization_options
-
).serializable_hash,
-
status: :created
-
else
-
render json: ErrorSerializer.new(variant).serializable_hash,
-
status: :unprocessable_entity
-
end
-
end
-
-
def index
-
serializer = CatalogueVariantSerializer.new(
-
CatalogueVariant.all, serialization_options
-
)
-
-
render json: serializer, status: :ok
-
end
-
-
def variants_params
-
params.permit(:catalogue_id, :catalogue_variant_color_id,
-
:catalogue_variant_size_id, :price, :stock_qty, :on_sale,
-
:sale_price, :discount_price, :decimal, :length, :breadth,
-
:height, :images)
-
end
-
-
def serialization_options
-
{params: {host: request.protocol + request.host_with_port}}
-
end
-
end
-
end
-
module BxBlockCatalogue
-
class CataloguesVariantsSizesController < ApplicationController
-
def create
-
sizes = CatalogueVariantSize.new(name: params[:name])
-
save_result = sizes.save
-
-
if save_result
-
render json: CatalogueVariantSizeSerializer.new(sizes)
-
.serializable_hash,
-
status: :created
-
else
-
render json: ErrorSerializer.new(sizes).serializable_hash,
-
status: :unprocessable_entity
-
end
-
end
-
-
def index
-
serializer = CatalogueVariantSizeSerializer.new(CatalogueVariantSize.all)
-
-
render json: serializer, status: :ok
-
end
-
end
-
end
-
module BxBlockCatalogue
-
class ReviewsController < ApplicationController
-
def create
-
review = Review.new(
-
catalogue_id: params[:catalogue_id],
-
rating: params[:rating],
-
comment: params[:comment]
-
)
-
save_result = review.save
-
-
if save_result
-
render json: ReviewSerializer.new(review).serializable_hash,
-
status: :created
-
else
-
render json: ErrorSerializer.new(review).serializable_hash,
-
status: :unprocessable_entity
-
end
-
end
-
-
def index
-
serializer = ReviewSerializer.new(Review.all)
-
-
render json: serializer, status: :ok
-
end
-
end
-
end
-
1
module BxBlockCatalogue
-
1
class StudyMaterialsController < ApplicationController
-
-
1
def video_and_assignment_for_student
-
4
if current_user.role.name == "Student"
-
3
class_division_id = current_user.class_division&.id
-
3
video_lectures = BxBlockCatalogue::VideosLecture.where(class_division_id: class_division_id)
-
3
assignments = BxBlockCatalogue::Assignment.where(class_division_id: class_division_id)
-
6
subjects = BxBlockCatalogue::Subject.all.map { |subject| { subject_name: subject.subject_name } }
-
3
type = params[:type]
-
3
filter_subject = params[:subject_name]
-
3
search_text = params[:video_search]
-
-
3
if type == 'video'
-
1
video_lectures = apply_video_filters(video_lectures, filter_subject, search_text)
-
1
video_lectures = video_lectures.page(params[:page]).per(params[:per_page])
-
1
render json: {
-
video_lectures: BxBlockCatalogue::VideoSerializer.new(video_lectures).serializable_hash,
-
video_count: video_lectures.count
-
}, status: :ok
-
2
elsif type == 'assignment'
-
1
assignments = apply_assignment_filters(assignments, filter_subject)
-
1
assignments = assignments.page(params[:page]).per(params[:per_page])
-
1
render json: {
-
assignments: BxBlockCatalogue::AssignmentSerializer.new(assignments).serializable_hash, assignment_count: assignments.count
-
}, status: :ok
-
else
-
1
render json: {
-
video_lectures: BxBlockCatalogue::VideoSerializer.new(video_lectures.page(params[:page]).per(params[:per_page])).serializable_hash,
-
assignments: BxBlockCatalogue::AssignmentSerializer.new(assignments.page(params[:page]).per(params[:per_page])).serializable_hash,
-
subjects: subjects, video_count: video_lectures.count, assignment_count: assignments.count
-
}, status: :ok
-
end
-
else
-
1
render json: { message: "You are not authorized "}, status: 422
-
end
-
end
-
-
1
def video_and_assignment(user_scope, type)
-
14
school = current_user.school
-
14
video_lectures = BxBlockCatalogue::VideosLecture.where(user_scope)
-
14
assignments = BxBlockCatalogue::Assignment.where(user_scope)
-
14
school_class = BxBlockCategories::SchoolClass.where(school_id: school.id).pluck(:class_number).uniq.sort
-
14
class_division = BxBlockCategories::ClassDivision.where(school_id: school.id).pluck(:division_name).uniq.sort
-
14
ebooks = BxBlockBulkUploading::EbookAllotment.where(user_scope)
-
14
search_class = params[:school_class]
-
14
search_division = params[:division]
-
-
14
@school_class = BxBlockCategories::SchoolClass.find_by(class_number: search_class)
-
14
@division = BxBlockCategories::ClassDivision.find_by(division_name: search_division, school_class_id: @school_class&.id)
-
14
case type
-
when 'video'
-
4
if search_class&.present? && search_division&.present?
-
2
video_lectures = video_lectures.where(school_class_id: @school_class&.id, class_division_id: @division&.id)
-
2
elsif search_class&.present?
-
2
video_lectures = video_lectures.where(school_class_id: @school_class&.id)
-
end
-
4
{ video_lectures: BxBlockCatalogue::VideoSerializer.new(video_lectures.page(params[:page]).per(params[:per_page])).serializable_hash,
-
video_count: video_lectures.count, school_class: school_class, class_division: class_division
-
}
-
when 'assignment'
-
4
if search_class&.present? && search_division&.present?
-
2
assignments = assignments.where(school_class_id: @school_class&.id, class_division_id: @division&.id)
-
2
elsif search_class&.present?
-
2
assignments = assignments.where(school_class_id: @school_class&.id)
-
end
-
4
{ assignments: BxBlockCatalogue::AssignmentSerializer.new(assignments.page(params[:page]).per(params[:per_page])).serializable_hash ,
-
assignment_count: assignments.count , school_class: school_class, class_division: class_division
-
}
-
when 'ebook'
-
4
if search_class&.present? && search_division&.present?
-
2
ebooks = ebooks.where(school_class_id: @school_class&.id, class_division_id: @division&.id)
-
2
elsif search_class&.present?
-
2
ebooks = ebooks.where(school_class_id: @school_class&.id)
-
end
-
4
{ ebook: BxBlockCatalogue::EbookAssignedSerializer.new(ebooks.page(params[:page]).per(params[:per_page])).serializable_hash,
-
ebook_count: ebooks.count , school_class: school_class, class_division: class_division
-
}
-
else
-
{
-
2
video_lectures: BxBlockCatalogue::VideoSerializer.new(video_lectures.page(params[:page]).per(params[:per_page])).serializable_hash,
-
assignments: BxBlockCatalogue::AssignmentSerializer.new(assignments.page(params[:page]).per(params[:per_page])).serializable_hash,
-
ebooks: BxBlockCatalogue::EbookAssignedSerializer.new(ebooks.page(params[:page]).per(params[:per_page])).serializable_hash,
-
ebook_count: ebooks.count,
-
video_count: video_lectures.count,
-
assignment_count: assignments.count , school_class: school_class, class_division: class_division
-
}
-
end
-
-
end
-
-
1
def video_and_assignment_for_teacher
-
8
if current_user.role.name == "Teacher"
-
7
user_scope = { account_id: current_user.id }
-
7
type = params[:type]
-
7
data = video_and_assignment(user_scope, type)
-
7
render json: data, status: :ok
-
else
-
1
render json: { message: "You are not authorized"}, status: 422
-
end
-
end
-
-
1
def video_and_assignment_for_school_admin
-
8
if current_user.role.name == "School Admin"
-
7
user_scope = { school_id: current_user.school_id }
-
7
type = params[:type]
-
7
data = video_and_assignment(user_scope, type)
-
7
render json: data, status: :ok
-
else
-
1
render json: { message: "You are not authorized"}, status: 422
-
end
-
end
-
-
1
def student_details(resource_type)
-
3
resource = nil
-
3
case resource_type
-
when 'video'
-
1
resource = BxBlockCatalogue::VideosLecture.find_by(id: params[:video_id])
-
when 'assignment'
-
1
resource = BxBlockCatalogue::Assignment.find_by(id: params[:assignment_id])
-
when 'ebook'
-
1
ebook_allotment = BxBlockBulkUploading::EbookAllotment.find_by(id: params[:assign_ebook_id])
-
1
resource = BxBlockBulkUploading::Ebook.find_by(id: ebook_allotment.ebook_id)
-
else
-
render json: { message: "Invalid type" }, status: 422
-
end
-
3
if resource_type == 'ebook'
-
1
students = AccountBlock::Account.where(role_id: BxBlockRolesPermissions::Role.where(name: "Student"))
-
.where(class_division_id: ebook_allotment&.class_division_id, school_class_id: ebook_allotment&.school_class_id, school_id: ebook_allotment&.school_id)
-
1
render json: {
-
ebook: BxBlockBulkUploading::EbookSerializer.new(resource).serializable_hash,
-
students: BxBlockCatalogue::StudentSerializer.new(students.page(params[:page]).per(params[:per_page]), serialization_options).serializable_hash,
-
students_count: students.count
-
}, status: :ok
-
else
-
2
students = AccountBlock::Account.where(role_id: BxBlockRolesPermissions::Role.where(name: "Student"))
-
.where(class_division_id: resource&.class_division_id, school_class_id: resource&.school_class_id, school_id: resource&.school_id)
-
-
2
render json: {
-
"#{resource_type}": "BxBlockCatalogue::#{resource_type.capitalize}Serializer".constantize.new(resource).serializable_hash,
-
students: BxBlockCatalogue::StudentSerializer.new(students.page(params[:page]).per(params[:per_page]), serialization_options).serializable_hash,
-
students_count: students.count
-
}, status: :ok
-
end
-
-
end
-
-
1
def student_details_video
-
1
student_details('video')
-
end
-
-
1
def student_details_assignment
-
1
student_details('assignment')
-
end
-
-
1
def student_details_ebook
-
1
student_details('ebook')
-
end
-
-
-
1
private
-
-
1
def apply_video_filters(video_lectures, filter_subject, search_text)
-
1
if filter_subject.present?
-
1
subject = BxBlockCatalogue::Subject.find_by(subject_name: filter_subject)
-
1
video_lectures = video_lectures.where(subject_id: subject&.id)
-
end
-
-
1
video_lectures = video_lectures.where('title LIKE ?', "%#{search_text}%") if search_text.present?
-
-
1
video_lectures
-
end
-
-
1
def apply_assignment_filters(assignments, filter_subject)
-
1
if filter_subject.present?
-
1
subject = BxBlockCatalogue::Subject.find_by(subject_name: filter_subject)
-
1
assignments = assignments.where(subject_id: subject&.id)
-
end
-
-
1
assignments
-
end
-
-
1
def serialization_options
-
3
{ params: { video_lecture_id: params[:video_id], assignment_id: params[:assignment_id], ebook_id: params[:assign_ebook_id] } }
-
end
-
-
1
def current_user
-
51
@account = AccountBlock::Account.find_by(id: @token.id)
-
end
-
end
-
end
-
module BxBlockCatalogue
-
class TagsController < ApplicationController
-
def create
-
tag = Tag.new(name: params[:name])
-
save_result = tag.save
-
-
if save_result
-
render json: TagSerializer.new(tag).serializable_hash,
-
status: :created
-
else
-
render json: ErrorSerializer.new(tag).serializable_hash,
-
status: :unprocessable_entity
-
end
-
end
-
-
def index
-
serializer = TagSerializer.new(Tag.all)
-
-
render json: serializer, status: :ok
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
1
module BxBlockCategories
-
1
class ApplicationController < BuilderBase::ApplicationController
-
1
include BuilderJsonWebToken::JsonWebTokenValidation
-
-
1
before_action :validate_json_web_token
-
-
1
rescue_from ActiveRecord::RecordNotFound, with: :not_found
-
-
1
private
-
-
1
def not_found
-
render json: {"errors" => ["Record not found"]}, status: :not_found
-
end
-
-
1
def current_user
-
return unless @token
-
-
@current_user ||= AccountBlock::Account.find(@token.id)
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
module BxBlockCategories
-
class CategoriesController < ApplicationController
-
before_action :load_category, only: %i[show update destroy]
-
-
def create
-
err = []
-
-
categories_params.map do |x|
-
name_validation = x.permit(:name).to_h
-
err << "name can't be blank" unless name_validation[:name].present?
-
end
-
-
return render json: {message: err.uniq}, status: :unprocessable_entity unless !err.present?
-
@categories = Category.create!(categories_params)
-
-
if @categories
-
render json: CategorySerializer.new(@categories, serialization_options)
-
.serializable_hash,
-
status: :created
-
end
-
rescue
-
categories_params.map do |x|
-
name_validation = x.permit(:name).to_h
-
if Category.where(name: name_validation[:name]).present?
-
err << "name can't be use #{name_validation[:name]}"
-
end
-
end
-
render json: {message: err}, status: :unprocessable_entity
-
end
-
-
def show
-
return if @category.nil?
-
-
render json: CategorySerializer.new(@category, serialization_options)
-
.serializable_hash,
-
status: :ok
-
end
-
-
def index
-
return render json: {message: "No data is present"}, status: :not_found unless Category.all.present?
-
serializer = if params[:sub_category_id].present?
-
categories = SubCategory.find(params[:sub_category_id])
-
.categories
-
CategorySerializer.new(categories)
-
else
-
CategorySerializer.new(Category.all, serialization_options)
-
end
-
render json: serializer, status: :ok
-
end
-
-
def destroy
-
return if @category.nil?
-
-
begin
-
if @category.destroy
-
remove_not_used_subcategories
-
-
render json: {success: true}, status: :ok
-
end
-
rescue ActiveRecord::InvalidForeignKey
-
message = "Record can't be deleted due to reference to a catalogue " \
-
"record"
-
-
render json: {
-
error: {message: message}
-
}, status: :internal_server_error
-
end
-
end
-
-
def update
-
return if @category.nil?
-
-
update_result = @category.update(update_categories_params)
-
-
if update_result
-
render json: CategorySerializer.new(@category).serializable_hash,
-
status: :ok
-
else
-
render json: ErrorSerializer.new(@category).serializable_hash,
-
status: :unprocessable_entity
-
end
-
end
-
-
def update_user_categories
-
categories = Category.where(id: params[:categories_ids])
-
category_ids = categories.map(&:id)
-
-
return render json: {errors: "Category ID #{(params[:categories_ids].map(&:to_i) - category_ids).join(",")} not found"}, status: :unprocessable_entity unless category_ids.count == params[:categories_ids].count
-
if categories.present?
-
UserCategory.where(account_id: current_user.id).delete_all
-
params[:categories_ids].each do |cat_id|
-
UserCategory.create!(account_id: current_user.id, category_id: cat_id)
-
end
-
categories = Category.joins(:user_categories).where(user_categories: {account_id: current_user.id})
-
render json: CategorySerializer.new(categories).serializable_hash,
-
status: :ok
-
end
-
end
-
-
private
-
-
def categories_params
-
params.permit(categories: [:name, light_icon: {}, light_icon_active: {}, light_icon_inactive: {}, dark_icon: {}, dark_icon_active: {}, dark_icon_inactive: {}]).require(:categories)
-
end
-
-
def update_categories_params
-
params.require(:categories).permit(:name, light_icon: {}, light_icon_active: {}, light_icon_inactive: {}, dark_icon: {}, dark_icon_active: {}, dark_icon_inactive: {})
-
end
-
-
def load_category
-
@category = Category.find_by(id: params[:id])
-
-
if @category.nil?
-
render json: {
-
message: "Category with id #{params[:id]} doesn't exists"
-
}, status: :not_found
-
end
-
end
-
-
def serialization_options
-
options = {}
-
options[:params] = {sub_categories: true}
-
options
-
end
-
-
def remove_not_used_subcategories
-
sql = "delete from sub_categories sc where sc.id in (
-
select sc.id from sub_categories sc
-
left join categories_sub_categories csc on
-
sc.id = csc.sub_category_id
-
where csc.sub_category_id is null
-
)"
-
ActiveRecord::Base.connection.execute(sql)
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
module BxBlockCategories
-
class CtaController < ApplicationController
-
before_action :assign_cta, only: [:index]
-
skip_before_action :validate_json_web_token, only: [:index]
-
-
def index
-
filter_cta
-
@ctas = @ctas.page(params[:page]).per(params[:per_page])
-
render json: CtaSerializer.new(@ctas).serializable_hash, status: :ok
-
end
-
-
private
-
-
def assign_cta
-
@ctas = Cta.includes(:category)
-
end
-
-
def filter_cta
-
params.each do |key, value|
-
case key
-
when "category"
-
@ctas = @ctas.where(categories: {id: value})
-
when "visible_on_details_page"
-
@ctas = @ctas.where(visible_on_details_page: true)
-
when "visible_on_home_page"
-
@ctas = @ctas.where(visible_on_home_page: true)
-
end
-
end
-
end
-
end
-
end
-
1
module BxBlockCategories
-
1
class SchoolsController < ApplicationController
-
1
skip_before_action :validate_json_web_token, only: [:index]
-
1
def index
-
1
@schools = BxBlockCategories::School.all
-
1
return render json: BxBlockCategories::SchoolSerializer.new(@schools)
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
module BxBlockCategories
-
class SubCategoriesController < ApplicationController
-
before_action :load_sub_category, only: %i[show update destroy]
-
-
def create
-
categories = Category.where(id: params[:parent_categories])
-
category_ids = categories.map(&:id)
-
-
return render json: {errors: "Category ID #{(params[:parent_categories].map(&:to_i) - category_ids).join(",")} not found"}, status: :not_found unless category_ids.count == params[:parent_categories].count
-
-
sub_category = SubCategory.new(name: params[:sub_category][:name])
-
if params[:parent_categories].present?
-
sub_category.categories << Category.where(
-
id: params[:parent_categories]
-
)
-
end
-
if sub_category.valid?
-
sub_category.save
-
-
render json: SubCategorySerializer.new(
-
sub_category,
-
serialization_options
-
).serializable_hash,
-
status: :created
-
else
-
render json: ErrorSerializer.new(sub_category).serializable_hash,
-
status: :unprocessable_entity
-
end
-
end
-
-
def show
-
return if @sub_category.nil?
-
-
render json: SubCategorySerializer.new(@sub_category).serializable_hash,
-
status: :ok
-
end
-
-
def index
-
return render json: {message: "No data is present"}, status: :not_found unless SubCategory.all.present?
-
serializer = if params[:category_id].present?
-
sub_categories = Category.find(params[:category_id])
-
.sub_categories
-
SubCategorySerializer.new(sub_categories)
-
else
-
SubCategorySerializer.new(
-
SubCategory.all,
-
serialization_options
-
)
-
end
-
-
render json: serializer, status: :ok
-
end
-
-
def destroy
-
return if @sub_category.nil?
-
-
begin
-
render json: {message: "sub category deleted successfully"}, status: :ok if @sub_category.destroy
-
rescue ActiveRecord::InvalidForeignKey
-
message = "Record can't be deleted due to reference to catalogue"
-
-
render json: {
-
error: {message: message}
-
}, status: :internal_server_error
-
end
-
end
-
-
def update
-
return if @sub_category.nil?
-
-
update_result = @sub_category.update(name: params[:sub_category][:name])
-
-
if update_result
-
render json: SubCategorySerializer.new(@sub_category).serializable_hash,
-
status: :ok
-
else
-
render json: ErrorSerializer.new(@sub_category).serializable_hash,
-
status: :unprocessable_entity
-
end
-
end
-
-
def update_user_sub_categories
-
sub_categories = SubCategory.where(id: params[:sub_categories_ids])
-
sub_category_ids = sub_categories.map(&:id)
-
-
return render json: {errors: "Sub Category ID #{(params[:sub_categories_ids].map(&:to_i) - sub_category_ids).join(",")} not found"}, status: :not_found unless sub_category_ids.count == params[:sub_categories_ids].count
-
if sub_categories.present?
-
UserSubCategory.where(account_id: current_user.id).delete_all
-
params[:sub_categories_ids].each do |sub_cat_id|
-
UserSubCategory.create!(account_id: current_user.id, sub_category_id: sub_cat_id)
-
end
-
sub_categories = SubCategory.joins(:user_sub_categories).where(user_sub_categories: {account_id: current_user.id})
-
render json: SubCategorySerializer.new(sub_categories).serializable_hash,
-
status: :ok
-
end
-
end
-
-
private
-
-
def load_sub_category
-
@sub_category = SubCategory.find_by(id: params[:id])
-
-
if @sub_category.nil?
-
render json: {
-
message: "SubCategory with id #{params[:id]} doesn't exists"
-
}, status: :not_found
-
end
-
end
-
-
def serialization_options
-
{}
-
# options[:params] = {categories: true}
-
end
-
end
-
end
-
module BxBlockCfhighlightingandunderliningtext
-
class ApplicationController < BuilderBase::ApplicationController
-
include BuilderJsonWebToken::JsonWebTokenValidation
-
-
before_action :validate_json_web_token
-
-
rescue_from ActiveRecord::RecordNotFound, :with => :not_found
-
-
private
-
-
def not_found
-
render :json => {'errors' => ['Record not found']}, :status => :not_found
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
module BxBlockComments
-
class ApplicationController < BuilderBase::ApplicationController
-
include BuilderJsonWebToken::JsonWebTokenValidation
-
include Pundit
-
include PublicActivity::StoreController
-
-
before_action :validate_json_web_token
-
-
rescue_from ActiveRecord::RecordNotFound, with: :not_found
-
-
def current_user
-
@current_user = AccountBlock::Account.find(@token.id)
-
rescue ActiveRecord::RecordNotFound
-
render json: {errors: [
-
{message: "Please login again."}
-
]}, status: :unprocessable_entity
-
end
-
-
private
-
-
def not_found
-
render json: {"errors" => ["Record not found"]}, status: :not_found
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
module BxBlockComments
-
class CommentsController < ApplicationController
-
before_action :current_user
-
before_action :load_comment, only: %i[like dislike show]
-
before_action :check_comment_type, only: [:create, :update]
-
-
def index
-
authorize BxBlockComments::Comment
-
condition = get_search_condition
-
comments = Comment.where(condition)
-
if comments.present?
-
render json: CommentSerializer.new(
-
comments,
-
{params: {current_user: current_user}}
-
).serializable_hash, status: :ok
-
else
-
render json: {
-
errors: [
-
{message: "No comments."}
-
]
-
}, status: :ok
-
end
-
end
-
-
def get_search_condition
-
condition = "account_id = #{current_user.id}"
-
condition += " and commentable_id = #{params[:commentable_id]}" if params[:commentable_id].present?
-
condition += " and commentable_type = '#{params[:commentable_type]}'" if params[:commentable_type].present?
-
condition
-
end
-
-
def search
-
@comments = Comment.where("comment ILIKE :search", search: "%#{search_params[:query]}%")
-
render json: CommentSerializer.new(
-
@comments, meta: {success: true, message: "Comment details."}
-
).serializable_hash, status: :ok
-
end
-
-
def show
-
authorize @comment
-
render json: CommentSerializer.new(
-
@comment,
-
meta: {success: true, message: "Comment details."},
-
params: {current_user: current_user}
-
).serializable_hash, status: :ok
-
end
-
-
def create
-
@comment = Comment.new(comment_params)
-
-
authorize @comment
-
@comment.account_id = current_user.id
-
if @comment.save
-
render json: CommentSerializer.new(
-
@comment,
-
meta: {
-
success: true, message: "Comment created."
-
},
-
params: {current_user: current_user}
-
).serializable_hash, status: :created
-
else
-
render json: {errors: format_activerecord_errors(@comment.errors)},
-
status: :unprocessable_entity
-
end
-
end
-
-
def update
-
@comment = Comment.find_by(id: params[:id], account_id: current_user.id)
-
-
unless @comment.present?
-
return render json: {
-
errors: [
-
{message: "Comment does not exist."}
-
]
-
}, status: :unprocessable_entity
-
end
-
-
authorize @comment
-
-
if @comment.update(comment: comment_params["comment"])
-
render json: CommentSerializer.new(
-
@comment,
-
meta: {
-
success: true, message: "Comment updated."
-
},
-
params: {current_user: current_user}
-
).serializable_hash, status: :ok
-
else
-
render json: {errors: format_activerecord_errors(@comment.errors)},
-
status: :unprocessable_entity
-
end
-
end
-
-
def destroy
-
@comment = Comment.find_by(id: params[:id], account_id: current_user.id)
-
-
unless @comment.present?
-
return render json: {
-
errors: [
-
{message: "Comment does not exist."}
-
]
-
}, status: :unprocessable_entity
-
end
-
-
authorize @comment
-
-
if @comment.destroy
-
render json: {message: "Comment deleted."}, status: :ok
-
else
-
render json: {errors: format_activerecord_errors(@comment.errors)},
-
status: :unprocessable_entity
-
end
-
end
-
-
private
-
-
def comment_params
-
params.require(:comment).permit(:commentable_id, :commentable_type, :comment)
-
end
-
-
def check_comment_type
-
commentable_type = params[:comment][:commentable_type]
-
unless commentable_type == "BxBlockPosts::Post" || commentable_type == "BxBlockComments::Comment"
-
render json: {error: "Only BxBlockComments::Comment or BxBlockPosts::Post can be used for comment type"},
-
status: :bad_request
-
end
-
end
-
-
def format_activerecord_errors(errors)
-
result = []
-
errors.each do |attribute, error|
-
result << {attribute => error}
-
end
-
result
-
end
-
-
def search_params
-
params.permit(:query)
-
end
-
-
def load_comment
-
@comment = BxBlockComments::Comment.find_by(id: params[:id])
-
if @comment.nil?
-
render json: {message: "Does not exist"},
-
status: :not_found
-
end
-
end
-
end
-
end
-
1
module BxBlockContactUs
-
1
class ApplicationController < BuilderBase::ApplicationController
-
1
include BuilderJsonWebToken::JsonWebTokenValidation
-
# before_action :validate_json_web_token
-
-
1
rescue_from ActiveRecord::RecordNotFound, :with => :not_found
-
-
1
private
-
-
1
def not_found
-
render :json => {'errors' => ['Record not found']}, :status => :not_found
-
end
-
end
-
end
-
1
module BxBlockContactUs
-
1
class ContactsController < ApplicationController
-
1
FORGOT_PASSWORD = "Forgot Password"
-
1
STUDENT = "Student"
-
1
TEACHER = "Teacher"
-
1
SCHOOL_ADMIN = "School Admin"
-
1
PUBLISHER = "Publisher"
-
-
1
def create
-
25
if ![PUBLISHER, TEACHER, SCHOOL_ADMIN, STUDENT].include?(params[:data][:type])
-
1
return render json: {errors: [
-
{account: "Invalid User Type"}
-
]}, status: :unprocessable_entity
-
end
-
-
24
if !params[:data][:email].present?
-
9
return render json: {errors: "please provide email id"}
-
end
-
-
15
message = (params[:data][:type] == 'School Admin') ? true : forgot_password
-
-
15
if message != true
-
4
return render json: {errors: message}
-
end
-
-
11
if params[:data][:issue] != FORGOT_PASSWORD && !params[:data][:name]
-
3
return render json: {errors: "please provide #{params[:data][:type]} name"}
-
end
-
-
8
if [PUBLISHER, TEACHER, SCHOOL_ADMIN].include?(params[:data][:type]) && params[:data][:issue] == FORGOT_PASSWORD
-
7
@account = AccountBlock::Account.where("lower (email) = ?", params[:data][:email].downcase).last
-
1
elsif params[:data][:type] == STUDENT && params[:data][:issue] == FORGOT_PASSWORD
-
@account = AccountBlock::Account.where(student_unique_id: params[:data][:unique_id]).last
-
end
-
8
@contact = Contact.create(contact_params)
-
8
check_issue(@account)
-
end
-
-
1
def forgot_password
-
11
if (params[:data][:type] == STUDENT || params[:data][:type] == TEACHER) && params[:data][:issue] == FORGOT_PASSWORD && !params[:data][:unique_id].present?
-
4
return "please provide #{params[:data][:type]} id"
-
end
-
-
7
if params[:data][:type] == SCHOOL_ADMIN && params[:data][:issue] == FORGOT_PASSWORD && !params[:data][:school_id].present?
-
return 'please provide school name'
-
end
-
7
return true
-
end
-
-
1
def forgot_password_issues
-
4
return 'Invalid email address' if invalid_email_address?
-
4
return 'Invalid unique id' if invalid_unique_id?
-
4
return 'please provide valid teacher id' if invalid_teacher_id?
-
3
return 'please provide valid guardian email' if invalid_guardian_email?
-
3
true
-
end
-
-
1
def invalid_email_address?
-
4
!@account.present? && params.dig(:data, :issue) == FORGOT_PASSWORD && params.dig(:data, :type) != STUDENT
-
end
-
-
1
def invalid_unique_id?
-
4
!@account.present? && params.dig(:data, :issue) == FORGOT_PASSWORD
-
end
-
-
1
def invalid_teacher_id?
-
4
@account.present? && params.dig(:data, :type) == TEACHER && @account.teacher_unique_id != params.dig(:data, :unique_id)
-
end
-
-
1
def invalid_guardian_email?
-
3
@account.present? && params.dig(:data, :type) == STUDENT && @account.guardian_email.downcase != params.dig(:data, :email).downcase
-
end
-
-
1
private
-
-
1
def check_issue(account)
-
8
if params[:data][:issue] != FORGOT_PASSWORD
-
1
render json: {message: 'your request has submitted successfully'}, status: :created
-
7
elsif account&.activated? && params[:data][:issue] == FORGOT_PASSWORD
-
4
issue = forgot_password_issues
-
4
if issue != true
-
1
return render json: {errors: issue}
-
end
-
3
create_email_otp(contact_params)
-
3
render json: {message: 'Please check your email for one time pin'}, status: :created
-
else
-
3
render json: {message: 'Please first activate your account'}
-
end
-
end
-
-
1
def send_email_for(otp_record)
-
3
BxBlockForgotPassword::EmailOtpMailer.with(otp: otp_record, host: request.base_url, incoming_params: params).otp_email.deliver
-
end
-
-
1
def create_email_otp(email)
-
3
email_otp = AccountBlock::EmailOtp.new(email: contact_params[:email])
-
-
3
if email_otp.save
-
3
@account.update(is_reset: true, one_time_pin: email_otp.pin , pin: email_otp.pin)
-
3
send_email_for(email_otp)
-
else
-
render json: { errors: [email_otp.errors] }, status: :unprocessable_entity
-
end
-
end
-
-
1
def contact_params
-
14
params.require(:data).permit(:name, :email, :phone_number, :description, :issue)
-
end
-
end
-
end
-
module BxBlockContentManagement
-
class ApplicationController < BuilderBase::ApplicationController
-
include JSONAPI::Deserialization
-
include BuilderJsonWebToken::JsonWebTokenValidation
-
-
before_action :validate_json_web_token
-
-
rescue_from ActiveRecord::RecordNotFound, :with => :not_found
-
-
around_action :set_locale
-
-
before_action :update_current_user
-
-
private
-
-
def not_found
-
render :json => {'errors' => [app_t('controllers.application.errors.record_not_found')]}, :status => :not_found
-
end
-
-
def assign_json_web_token
-
token = request.headers[:token] || params[:token]
-
begin
-
@token = BuilderJsonWebToken::JsonWebToken.decode(token)
-
rescue *ERROR_CLASSES => exception
-
end
-
end
-
-
def current_user
-
return unless @token
-
account_id = @token.id
-
account = AccountBlock::Account.find(account_id)
-
end
-
-
def set_locale
-
lang = params[:language] || I18n.default_locale
-
Globalize.with_locale(lang) do
-
yield
-
end
-
end
-
-
def format_activerecord_errors(errors)
-
[{ error: errors.full_messages.first }]
-
end
-
-
def app_t(key)
-
BxBlockLanguageOptions::ApplicationMessage.translation_message(key)
-
end
-
-
def update_current_user
-
current_user.update(last_visit_at: Time.now) if current_user.present?
-
end
-
end
-
end
-
module BxBlockContentManagement
-
class AuthorsController < ApplicationController
-
skip_before_action :validate_json_web_token, only: [:show, :index]
-
-
def show
-
@author = BxBlockContentManagement::Author.find_by(id: params[:id])
-
render json: BxBlockContentManagement::AuthorSerializer.new(@author).serializable_hash, status: :ok
-
end
-
-
def index
-
content_types = BxBlockContentManagement::Author.all.page(params[:page]).per(params[:per_page])
-
render json: BxBlockContentManagement::AuthorSerializer.new(content_types).serializable_hash, status: :ok
-
end
-
end
-
end
-
module BxBlockContentManagement
-
class BookmarksController < ApplicationController
-
before_action :validate_json_web_token, only: [:create, :destroy, :index]
-
-
def create
-
bookmark = current_user.bookmarks.new(content_id: params[:content_id])
-
-
if bookmark.save
-
render json: BxBlockContentManagement::BookmarkSerializer.new(bookmark).serializable_hash,
-
status: :created
-
else
-
render json: BxBlockContentManagement::ErrorSerializer.new(bookmark).serializable_hash,
-
status: :unprocessable_entity
-
end
-
end
-
-
def index
-
contents = current_user.content_followings
-
render json: BxBlockContentManagement::ContentSerializer.new(contents, serialization_options).serializable_hash,
-
status: :ok
-
end
-
-
def destroy
-
follow = current_user.bookmarks.find(params[:id])
-
if follow.destroy
-
render json: { success: true }, status: :ok
-
else
-
render json: BxBlockContentManagement::ErrorSerializer.new(follow).serializable_hash,
-
status: :unprocessable_entity
-
end
-
end
-
-
private
-
def serialization_options
-
options = {}
-
options[:params] = { current_user_id: current_user&.id}
-
options
-
end
-
end
-
end
-
module BxBlockContentManagement
-
class ContentProvidersController < ApplicationController
-
skip_before_action :validate_json_web_token, only: [:index]
-
end
-
end
-
module BxBlockContentManagement
-
class ContentTypesController < ApplicationController
-
skip_before_action :validate_json_web_token, only: [:index]
-
-
def index
-
content_types = BxBlockContentManagement::ContentType.all.order(:rank).page(params[:page]).per(params[:per_page])
-
render json: BxBlockContentManagement::ContentTypeSerializer.new(content_types).serializable_hash, status: :ok
-
end
-
end
-
end
-
module BxBlockContentManagement
-
class ContentsController < ApplicationController
-
before_action :assign_contents, only: [:index, :show]
-
skip_before_action :validate_json_web_token, only: [:get_content_detail, :index, :show,
-
:reindex_contents, :run_seeds]
-
before_action :authorize_request, only: [:reindex_contents, :run_seeds]
-
before_action :set_category, :set_sub_category, :set_content_type, :set_language, only: [:contents]
-
-
def get_content_detail
-
@content_type_id = params[:id]
-
content_type_obj = BxBlockContentManagement::ContentType.find_by(id: params["id"])
-
@content_type = content_type_obj&.type
-
@content_name = content_type_obj&.name
-
-
if params[:content_id].present?
-
@contentable = BxBlockContentManagement::Content.find_by(id: params[:content_id])&.contentable
-
end
-
if @content_type.present?
-
render 'rails_admin/application/form_template'
-
end
-
end
-
-
def contents
-
tags = params[:tag_list]
-
content = BxBlockContentManagement::CreateContentService.create_content(
-
@content_type, content_params, @sub_category, @language, @category, tags
-
)
-
if content.present? && content[:errors].present?
-
render json: {errors: content[:errors], status: 404}
-
else
-
render json: {content: ContentSerializer.new(content).serializable_hash, success: true,
-
message: "Content created successfully!"}
-
end
-
end
-
-
def index
-
filter_content
-
if params[:search].present?
-
@contents = Content.search(
-
params[:search], misspellings: true, page: params[:page], per_page: params[:per_page],
-
where: { id: @contents.ids }
-
)
-
else
-
@contents = @contents.page(params[:page]).per(params[:per_page])
-
end
-
render json: ContentSerializer.new(@contents, serialization_options).serializable_hash, status: :ok
-
end
-
-
def show
-
@content = @contents.find(params[:id])
-
@content.update(view_count: @content.view_count + 1)
-
render json: ContentSerializer.new(@content).serializable_hash, status: :ok
-
end
-
-
def reindex_contents
-
BxBlockContentManagement::Content.reindex
-
render json: { message: "Content reindexed Successfully!" }
-
end
-
-
def run_seeds
-
load Rails.root + "db/seeds.rb"
-
render json: { message: "Successfully! run seeds" }
-
end
-
-
private
-
-
def assign_contents
-
@contents = BxBlockContentManagement::Content.published.includes(
-
:category, :sub_category, :content_type, :language
-
)
-
end
-
-
def set_category
-
@category = BxBlockCategories::Category.find_by(id: params[:category_id])
-
unless @category.present?
-
return render json: {error: "can't find category with this id '#{params[:category_id]}'"}
-
end
-
end
-
-
def content_params
-
params.permit(:category_id, :sub_category_id, :language_id, :author_id, :headline,
-
:description, :feature_article, :feature_video, :searchable_text,
-
:content_type_id, :archived, :status, :publish_date, :tag_list,
-
:heading, :content, :hyperlink, :affiliation, :separate_section,
-
images_attributes: [:image], videos_attributes: [:video],
-
image_attributes: [:image], audio_attributes: [:audio],
-
pdfs_attributes: [:pdf], video_attributes: [:video])
-
end
-
-
def set_sub_category
-
@sub_category = BxBlockCategories::SubCategory.find_by(id: params[:sub_category_id])
-
unless @sub_category.present?
-
return render json: {error: "can't find sub category with this id '#{params[:sub_category_id]}'"}
-
end
-
end
-
-
def set_content_type
-
@content_type = BxBlockContentManagement::ContentType.find_by(id: params[:content_type_id])
-
unless @content_type.present?
-
return render json: {error: "can't find content type with this id '#{params[:content_type_id]}'"}
-
end
-
end
-
-
def set_language
-
@language = BxBlockLanguageOptions::Language.find_by(id: params[:language_id])
-
unless @language.present?
-
return render json: {error: "can't find language with this id '#{params[:language_id]}'"}
-
end
-
end
-
-
def filter_content
-
params.each do |key, value|
-
case key
-
when 'content_type'
-
@contents = @contents.where(content_types: {id: value})
-
when 'category'
-
@contents = @contents.where(categories: {id: value})
-
when 'date'
-
@contents = @contents.where(
-
"(publish_date < ?) and (publish_date > ?)", value["to"].to_datetime, value["from"].to_datetime
-
)
-
when 'feature_article'
-
@contents = @contents.where(feature_article: value)
-
when 'feature_video'
-
@contents = @contents.where(feature_video: value)
-
when 'content_language'
-
@contents = @contents.where(languages: {id: value})
-
when 'sub_category'
-
@contents = @contents.where(sub_categories: {id: value})
-
when 'tag'
-
@contents = @contents.tagged_with(value, any: true)
-
when 'content_provider'
-
@contents = @contents.where(admin_user_id: value)
-
end
-
end
-
end
-
-
def serialization_options
-
assign_json_web_token
-
options = {}
-
options[:params] = { current_user_id: (current_user&.id)}
-
options
-
end
-
-
def authorize_request
-
return render json: {data: [
-
{account: "Please use correct api_access_key."},
-
]}, status: 401 unless Rails.application.secrets.api_access_key == params[:api_access_key]
-
end
-
end
-
end
-
module BxBlockContentManagement
-
class ExamsController < ApplicationController
-
before_action :assign_exams, only: [:index, :show]
-
skip_before_action :validate_json_web_token, only: [:index, :show]
-
-
def index
-
filter_exam
-
render json: ExamSerializer.new(@exams).serializable_hash, status: :ok
-
end
-
-
def show
-
@exam = @exams.find_by(id: params[:id])
-
render json: ExamSerializer.new(@exam).serializable_hash, status: :ok
-
end
-
-
private
-
-
def filter_exam
-
params.each do |key, value|
-
case key
-
when 'date'
-
@exams = @exams.where(:to => value["to"].to_date..value["from"].to_date).or(
-
@exams.where(:from => value["to"].to_date..value["from"].to_date)
-
)
-
end
-
end
-
end
-
-
def assign_exams
-
@exams = BxBlockContentManagement::Exam.all
-
end
-
end
-
end
-
module BxBlockContentManagement
-
class FollowsController < ApplicationController
-
before_action :validate_json_web_token, only: [:create, :destroy, :index, :followers_content]
-
-
def create
-
follow = current_user.followers.new(content_provider_id: params[:content_provider_id])
-
-
if follow.save
-
render json: FollowSerializer.new(follow).serializable_hash,
-
status: :created
-
else
-
render json: ErrorSerializer.new(follow).serializable_hash,
-
status: :unprocessable_entity
-
end
-
end
-
-
def index
-
render json: BxBlockContentManagement::ContentProviderSerializer.new(
-
current_user.content_provider_followings, serialization_options
-
).serializable_hash, status: :ok
-
end
-
-
def destroy
-
follow = current_user.followers.find(params[:id])
-
if follow.destroy
-
render json: { success: true }, status: :ok
-
else
-
render json: ErrorSerializer.new(follow).serializable_hash,
-
status: :unprocessable_entity
-
end
-
end
-
-
private
-
def serialization_options
-
options = {}
-
options[:params] = { current_user_id: current_user&.id}
-
options
-
end
-
end
-
end
-
module BxBlockContentManagement
-
class TagsController < ApplicationController
-
skip_before_action :validate_json_web_token, only: [:index]
-
-
def index
-
tags = ActsAsTaggableOn::Tag.all.page(params[:page]).per(params[:per_page])
-
render json: TagSerializer.new(tags).serializable_hash, status: :ok
-
end
-
end
-
end
-
module BxBlockCors
-
class ApplicationController < BuilderBase::ApplicationController
-
# protect_from_forgery with: :exception
-
end
-
end
-
module BxBlockCouponCg
-
class ApplicationController < BuilderBase::ApplicationController
-
include BuilderJsonWebToken::JsonWebTokenValidation
-
-
before_action :validate_json_web_token
-
-
rescue_from ActiveRecord::RecordNotFound, :with => :not_found
-
-
private
-
-
def not_found
-
render :json => {'errors' => ['Record not found']}, :status => :not_found
-
end
-
end
-
end
-
module BxBlockCouponCg
-
class CouponCodeGeneratorController < ApplicationController
-
before_action :load_coupon, only: [:show, :update, :destroy]
-
-
def create
-
coupon = CouponCode.new(coupon_params)
-
save_result = coupon.save
-
-
if save_result
-
render json: CouponCodeSerializer.new(coupon).serializable_hash,
-
status: :ok
-
else
-
render json: ErrorSerializer.new(coupon).serializable_hash,
-
status: :unprocessable_entity
-
end
-
end
-
-
def show
-
return if @coupon.nil?
-
-
render json: CouponCodeSerializer.new(@coupon).serializable_hash,
-
status: :ok
-
end
-
-
def index
-
coupons = CouponCode.all
-
serializer = CouponCodeSerializer.new(coupons)
-
-
render json: serializer, status: :ok
-
end
-
-
def destroy
-
return if @coupon.nil?
-
-
if @coupon.destroy
-
render json: {}, status: :ok
-
else
-
render json: ErrorSerializer.new(@coupon).serializable_hash,
-
status: :unprocessable_entity
-
end
-
end
-
-
def update
-
return if @coupon.nil?
-
-
update_result = @coupon.update(coupon_params)
-
-
if update_result
-
render json: CouponCodeSerializer.new(@coupon).serializable_hash,
-
status: :ok
-
else
-
render json: ErrorSerializer.new(@coupon).serializable_hash,
-
status: :unprocessable_entity
-
end
-
end
-
-
private
-
-
def load_coupon
-
@coupon = CouponCode.find_by(id: params[:id])
-
-
if @coupon.nil?
-
render json: {
-
message: "Coupon with id #{params[:id]} doesn't exists"
-
}, status: :not_found
-
end
-
end
-
-
def coupon_params
-
params.require(:data).permit(:title, :description, :code, :discount_type,
-
:discount, :valid_from, :valid_to, :min_cart_value,
-
:max_cart_value)
-
end
-
end
-
end
-
-
module BxBlockDashboard
-
class ApplicationController < BuilderBase::ApplicationController
-
-
end
-
end
-
module BxBlockDashboard
-
class CandidatesController < BxBlockDashboard::ApplicationController
-
def index
-
@candidate = BxBlockDashboard::Candidate.last
-
total_count = BxBlockDashboard::Candidate.count
-
render json: BxBlockDashboard::CandidateSerializer.new(@candidate, params: { total_candidates: total_count }) , status: :ok
-
end
-
-
def create
-
@candidate = BxBlockDashboard::Candidate.new(candidate_params)
-
if @candidate.save
-
render json: BxBlockDashboard::CandidateSerializer.new(@candidate), status: :created
-
else
-
render json: { errors: @candidate.errors }, status: :unprocessable_entity
-
end
-
end
-
-
private
-
-
def candidate_params
-
params.require(:candidate).permit(:name,:email,:address)
-
end
-
end
-
end
-
module BxBlockDashboardguests
-
class ApplicationController < BuilderBase::ApplicationController
-
include BuilderJsonWebToken::JsonWebTokenValidation
-
-
before_action :validate_json_web_token
-
-
rescue_from ActiveRecord::RecordNotFound, :with => :not_found
-
-
private
-
-
def not_found
-
render :json => {'errors' => ['Record not found']}, :status => :not_found
-
end
-
end
-
end
-
module BxBlockDashboardguests
-
class CompaniesController < ApplicationController
-
skip_before_action :validate_json_web_token, only: [:show, :index]
-
before_action :load_company, only: [:show, :update, :destroy]
-
-
def index
-
companies = Company.all
-
render json: CompanySerializer.new(companies, params: { host: request.protocol + request.host_with_port }), status: :ok
-
end
-
-
def create
-
@company = Company.new(company_params)
-
user = AccountBlock::Account.find(@token.id)
-
@company.company_holder = user&.full_name.present? ? user&.full_name : " "
-
if @company.save
-
render json: CompanySerializer.new(@company, params: { host: request.protocol + request.host_with_port }).serializable_hash, status: :created
-
else
-
render json: {'errors' => [@company.errors.full_messages.to_sentence]}, status: :unprocessable_entity
-
end
-
end
-
-
def show
-
render json: CompanySerializer.new(@company, params: { host: request.protocol + request.host_with_port }).serializable_hash, status: :ok
-
end
-
-
def destroy
-
@company.destroy
-
render json: { success: true }, status: :ok
-
end
-
-
def update
-
if @company.update(company_params)
-
render json: CompanySerializer.new(@company, params: { host: request.protocol + request.host_with_port }), status: :ok
-
else
-
render json: {'errors' => [@company.errors.full_messages.to_sentence]}, status: :unprocessable_entity
-
end
-
end
-
-
private
-
-
def load_company
-
@company = Company.find_by(id: params[:id])
-
if @company.nil?
-
return render json: {
-
message: "Company with id #{params[:id]} doesn't exists"
-
}, status: :not_found
-
end
-
end
-
-
def company_params
-
params.require(:data).permit(:company_name, :doc)
-
end
-
end
-
end
-
module BxBlockDashboardguests
-
class DashboardGuestsController < ApplicationController
-
skip_before_action :validate_json_web_token, only: [:show, :index, :portfolio]
-
before_action :load_guest, only: [:show, :update, :destroy]
-
-
def index
-
guests = DashboardGuest.all
-
render json: DashboardGuestSerializer.new(guests, params: { host: request.protocol + request.host_with_port }), status: :ok
-
end
-
-
def portfolio
-
account = AccountBlock::Account.find_by(uniq_id: params[:uniq_id].to_s)
-
render json: DashboardGuestSerializer.new(account.bx_block_dashboardguests_dashboard_guests, params: { host: request.protocol + request.host_with_port }), status: :ok
-
end
-
-
def create
-
@guest = DashboardGuest.new(guest_params.merge(account_id: @token.id))
-
if @guest.save
-
render json: DashboardGuestSerializer.new(@guest, params: { host: request.protocol + request.host_with_port }).serializable_hash, status: :created
-
else
-
render json: {'errors' => [@guest.errors.full_messages.to_sentence]}, status: :unprocessable_entity
-
end
-
end
-
-
def show
-
render json: DashboardGuestSerializer.new(@guest, params: { host: request.protocol + request.host_with_port }).serializable_hash, status: :ok
-
end
-
-
def destroy
-
@guest.destroy
-
render json: { success: true }, status: :ok
-
end
-
-
def update
-
if @guest.update(guest_params)
-
render json: DashboardGuestSerializer.new(@guest, params: { host: request.protocol + request.host_with_port }), status: :ok
-
else
-
render json: {'errors' => [@guest.errors.full_messages.to_sentence]}, status: :unprocessable_entity
-
end
-
end
-
-
private
-
-
def load_guest
-
@guest = DashboardGuest.find_by(id: params[:id])
-
if @guest.nil?
-
return render json: {
-
message: "Guest with id #{params[:id]} doesn't exists"
-
}, status: :not_found
-
end
-
end
-
-
def guest_params
-
params.require(:data).permit(:company_id, :invest_amount, :date_of_invest)
-
end
-
end
-
end
-
module BxBlockDatastorage
-
class ApplicationController < BuilderBase::ApplicationController
-
include BuilderJsonWebToken::JsonWebTokenValidation
-
-
before_action :validate_json_web_token
-
-
rescue_from ActiveRecord::RecordNotFound, :with => :not_found
-
-
def format_activerecord_errors(errors)
-
result = []
-
errors.each do |attribute, error|
-
result << { attribute => error }
-
end
-
result
-
end
-
-
private
-
-
def not_found
-
render :json => {'errors' => ['Record not found']}, :status => :not_found
-
end
-
-
def current_user
-
@current_user ||= AccountBlock::Account.find(@token.id)
-
rescue ActiveRecord::RecordNotFound
-
render json: {
-
errors: [{message: "Authentication token invalid"}]
-
}, status: :unprocessable_entity
-
end
-
end
-
end
-
module BxBlockDatastorage
-
class FileDocumentsController < ApplicationController
-
include BuilderJsonWebToken::JsonWebTokenValidation
-
before_action :validate_json_web_token
-
-
def create
-
file_documents = current_user.file_documents.new(create_document_params)
-
if file_documents.save
-
render json: FileDocumentSerializer.new(file_documents).serializable_hash, status: 200
-
else
-
render json: {errors: format_activerecord_errors(file_documents.errors)}, status: :unprocessable_entity
-
end
-
end
-
-
def index
-
file_documents = current_user.file_documents.order(created_at: :desc)
-
if file_documents.present?
-
render json: FileDocumentSerializer.new(file_documents).serializable_hash, status: 200
-
else
-
render json: { message: t('file_document_not_found') },status: :unprocessable_entity
-
end
-
end
-
-
def show
-
file_document = FileDocument.find_by(id: params[:id])
-
if file_document.present?
-
render json: FileDocumentSerializer.new(file_document).serializable_hash, status: 200
-
else
-
render json: { message: t('file_document_not_found') },status: :unprocessable_entity
-
end
-
end
-
-
def destroy
-
file_document = FileDocument.find_by(id: params[:id])
-
if file_document.present?
-
file_document.destroy
-
render json: { message: "File document successfully removed" }, status: 200
-
else
-
render json: { message: t('file_document_not_found') },status: :unprocessable_entity
-
end
-
end
-
-
-
private
-
-
def create_document_params
-
params.require(:file_document).permit(:title, :description, :document_type, attachments: [])
-
end
-
end
-
end
-
module BxBlockDocumentopener2
-
class ApplicationController < BuilderBase::ApplicationController
-
include BuilderJsonWebToken::JsonWebTokenValidation
-
-
before_action :validate_json_web_token
-
-
rescue_from ActiveRecord::RecordNotFound, :with => :not_found
-
-
private
-
-
def not_found
-
render :json => {'errors' => ['Record not found']}, :status => :not_found
-
end
-
end
-
end
-
1
module BxBlockDocumentstorage2
-
1
class ApplicationController < BuilderBase::ApplicationController
-
1
include BuilderJsonWebToken::JsonWebTokenValidation
-
-
1
before_action :validate_json_web_token
-
-
1
rescue_from ActiveRecord::RecordNotFound, :with => :not_found
-
-
1
private
-
-
1
def not_found
-
render :json => {'errors' => ['Record not found']}, :status => :not_found
-
end
-
end
-
end
-
-
1
module BxBlockDocumentstorage2
-
1
class MyBookStoresController < ApplicationController
-
-
1
def show_bundle
-
1
bundles = BxBlockBulkUploading::BundleManagement.all.page(params[:page]).per(params[:per_page])
-
1
render json: serialize_bundles(bundles)
-
end
-
-
1
def show_ebooks
-
1
account = AccountBlock::Account.find_by(id: @token.id)
-
1
@collections = BxBlockBulkUploading::Ebook.all.page(params[:page]).per(params[:per_page])
-
-
1
if params[:subject].present?
-
1
@collections = @collections.where(subject: params[:subject])
-
end
-
-
1
if params[:search_term].present?
-
1
search_term = params[:search_term].downcase
-
1
@collections = @collections.where("LOWER(title) LIKE ? OR LOWER(author) LIKE ?", "%#{search_term}%", "%#{search_term}%")
-
end
-
-
1
if @collections.any?
-
1
ebooks_data = @collections.map do |ebook|
-
{
-
1
id: ebook.id,
-
title: ebook.title,
-
author: ebook.author,
-
price: ebook.price,
-
subject: ebook.subject,
-
1
cover_image_url: ebook.images.map { |image| url_for(image) }
-
}
-
end
-
-
1
if account.role.name == "Student"
-
ebooks_allotted_to_student = BxBlockBulkUploading::EbookAllotment.where(student_id: account.id).includes(:ebook)
-
unique_alloted_ebook_ids = ebooks_allotted_to_student.pluck(:ebook_id).uniq
-
-
ebooks_data.each do |ebook|
-
ebook[:assigned] = unique_alloted_ebook_ids.include?(ebook[:id])
-
end
-
end
-
1
subjects = BxBlockCatalogue::Subject.all
-
1
subjects_data = subjects.map { |subject| { id: subject.id, name: subject.subject_name } }
-
1
unique_subjects = subjects_data.uniq { |subject| subject[:name] }
-
1
render json: { all_data: ebooks_data, subject: unique_subjects }, status: :ok
-
end
-
end
-
-
1
def show_one_book_details
-
1
@ebook = BxBlockBulkUploading::Ebook.find(params[:id])
-
-
1
if @ebook.present?
-
1
render json: BxBlockBulkUploading::EbookSerializer.new(@ebook, serialization_options).serializable_hash, status: :ok
-
end
-
end
-
-
1
def show_one_bundle_details
-
1
bundle = BxBlockBulkUploading::BundleManagement.find(params[:id])
-
1
render json: serialize_one_bundle(bundle)
-
end
-
-
-
-
1
private
-
-
1
def serialize_one_bundle(bundle)
-
{
-
1
id: bundle.id,
-
title: bundle.title,
-
description: bundle.description,
-
total_pricing: bundle.ebooks.sum(:price),
-
books_count:bundle.ebooks.count,
-
board: bundle.board,
-
school_class_id: bundle.school_class_id,
-
books: bundle.ebooks.pluck(:title),
-
1
cover_images: bundle.cover_images.map { |image| url_for(image) }
-
}
-
end
-
-
1
def serialize_bundles(bundles)
-
1
bundle_data = bundles.map do |bundle|
-
{
-
5
id: bundle.id,
-
title: bundle.title,
-
board: bundle.ebooks.pluck(:board).uniq.join(", "),
-
class: bundle.ebooks.pluck(:school_class_id).uniq.join(", "),
-
total_books: bundle.ebooks.count,
-
total_price: bundle.ebooks.sum(:price),
-
5
cover_images: bundle.cover_images.map { |image| url_for(image) }
-
}
-
end
-
{
-
1
bundles: bundle_data,
-
total_count: bundles.count
-
}
-
end
-
-
-
1
def serialization_options
-
1
{ params: { host: request.protocol + request.host_with_port } }
-
end
-
end
-
end
-
module BxBlockDownload
-
class ApplicationController < BuilderBase::ApplicationController
-
-
# before_action :validate_json_web_token, :current_user
-
-
# rescue_from ActiveRecord::RecordNotFound, :with => :not_found
-
-
# private
-
-
# def not_found
-
# render :json => {'errors' => ['Record not found']}, :status => :not_found
-
# end
-
-
end
-
end
-
module BxBlockDownload
-
class DownloadablesController < ApplicationController
-
include Rails.application.routes.url_helpers
-
-
before_action :validate_json_web_token, :current_user
-
before_action :set_downloadable
-
-
def upload
-
if @downloadable.nil?
-
@downloadable = BxBlockDownload::Downloadable.new(downloadable_params)
-
end
-
if params[:files].present?
-
validated, invalid_files = validate_files(params[:files])
-
if validated
-
params[:files].each do |file|
-
@downloadable.files.attach(file)
-
end
-
if @downloadable.save
-
render status: :ok, json: { downloadable: BxBlockDownload::DownloadablesSerializer.new(@downloadable).serializable_hash, message: "File/s uploaded successfully." }
-
else
-
render status: :unprocessable_entity, json: { errors: @downloadable.errors }
-
end
-
else
-
render status: :bad_request, json: { message: "Not saved! Invalid file format.", files: invalid_files }
-
end
-
else
-
render status: :bad_request, json: { message: "File not selected." }
-
end
-
end
-
-
def view_downloadables
-
unless @downloadable.nil?
-
render json: { downloadable: BxBlockDownload::DownloadablesSerializer.new(@downloadable) }
-
else
-
downloadable_not_found
-
end
-
end
-
-
def download
-
if @downloadable.nil?
-
downloadable_not_found
-
else
-
get_file
-
unless @file.nil?
-
url = Rails.application.routes.url_helpers.rails_blob_url(@file)
-
@downloadable.update(last_download_at: DateTime.now)
-
@file.update(downloaded_at: DateTime.now)
-
begin
-
redirect_to "#{url}"
-
rescue => e
-
e.inspect
-
end
-
else
-
file_not_found
-
end
-
end
-
end
-
-
def destroy
-
if is_downloadable?
-
if @downloadable.destroy
-
render json: { message: "Downloadable deleted." }
-
else
-
render json: { message: "something went wrong.", error: @downloadable.errors }
-
end
-
end
-
end
-
-
def delete_file
-
if is_downloadable?
-
get_file
-
if @file.nil?
-
file_not_found
-
else
-
@file.purge
-
render json: { downloadable: BxBlockDownload::DownloadablesSerializer.new(@downloadable), message: "File deleted." }
-
end
-
end
-
end
-
-
private
-
-
def set_downloadable
-
@downloadable = BxBlockDownload::Downloadable.find_by(reference_id: params[:reference_id], reference_type: params[:reference_type])
-
end
-
-
def downloadable_params
-
params.permit(:files, :reference_type, :reference_id)
-
end
-
-
def get_file
-
@file = @downloadable.files.find_by(id: params[:file_id])
-
end
-
-
def is_downloadable?
-
if @downloadable.nil?
-
downloadable_not_found
-
false
-
else
-
true
-
end
-
end
-
-
def downloadable_not_found
-
render status: :not_found, json: { errors:{ message: "Downloadable not found." } }
-
end
-
-
def file_not_found
-
render status: :not_found, json: { message: "File with id #{params[:file_id]} not found." }
-
end
-
-
def validate_files(files)
-
# add allowed file types
-
allowed = ["application/msword","application/vnd.openxmlformats-officedocument.wordprocessingml.document","application/pdf","image/jpeg","image/jpg","image/png", "pdf", "png", "jpg", "jpeg", "doc", "docx"]
-
invalid_files = []
-
validate = true
-
if files.count > 0
-
files.each do |file|
-
content_type = file.content_type
-
if content_type == ""
-
content_type = file.original_filename.split(".").last
-
end
-
unless allowed.include?(content_type)
-
invalid_files << (file.original_filename)
-
validate = false
-
end
-
end
-
else
-
render status: :bad_request, json: { errors: "Select atleast one" }
-
return false, invalid_files
-
end
-
return validate, invalid_files
-
end
-
end
-
end
-
1
module BxBlockElasticsearch
-
1
class ApplicationController < BuilderBase::ApplicationController
-
1
include BuilderJsonWebToken::JsonWebTokenValidation
-
# before_action :validate_json_web_token
-
-
1
rescue_from ActiveRecord::RecordNotFound, :with => :not_found
-
-
1
private
-
-
1
def not_found
-
render :json => {'errors' => ['Record not found']}, :status => :not_found
-
end
-
end
-
end
-
-
module BxBlockElasticsearch
-
class BxBlockElasticsearch::ArticlesController < ApplicationController
-
before_action :set_article, only: %i[ show edit update destroy ]
-
-
# GET /articles or /articles.json
-
def index
-
@articles = BxBlockElasticsearch::Article.all
-
end
-
-
# GET /articles/1 or /articles/1.json
-
def show
-
#This is auto generated show method
-
end
-
-
# GET /articles/new
-
def new
-
@article = BxBlockElasticsearch::Article.new
-
end
-
-
# GET /articles/1/edit
-
def edit
-
#This is auto generated edit method
-
end
-
-
# POST /articles or /articles.json
-
def create
-
@article = BxBlockElasticsearch::Article.new(article_params)
-
-
respond_to do |format|
-
if @article.save
-
format.html { redirect_to article_url(@article), notice: "Article was successfully created." }
-
format.json { render :show, status: :created, location: @article }
-
else
-
format.html { render :new, status: :unprocessable_entity }
-
format.json { render json: @article.errors, status: :unprocessable_entity }
-
end
-
end
-
end
-
-
# PATCH/PUT /articles/1 or /articles/1.json
-
def update
-
respond_to do |format|
-
if @article.update(article_params)
-
format.html { redirect_to article_url(@article), notice: "Article was successfully updated." }
-
format.json { render :show, status: :ok, location: @article }
-
else
-
format.html { render :edit, status: :unprocessable_entity }
-
format.json { render json: @article.errors, status: :unprocessable_entity }
-
end
-
end
-
end
-
-
# DELETE /articles/1 or /articles/1.json
-
def destroy
-
@article.destroy
-
-
respond_to do |format|
-
format.html { redirect_to articles_url, notice: "Article was successfully destroyed." }
-
format.json { head :no_content }
-
end
-
end
-
-
private
-
# Use callbacks to share common setup or constraints between actions.
-
def set_article
-
@article = BxBlockElasticsearch::Article.find(params[:id])
-
end
-
-
# Only allow a list of trusted parameters through.
-
def article_params
-
params.require(:article).permit(:title, :text)
-
end
-
end
-
end
-
1
module BxBlockElasticsearch
-
1
class SearchController < ApplicationController
-
1
before_action :validate_json_web_token, :current_user
-
1
respond_to? :html, :json
-
-
1
def search_content
-
11
@term = params[:term]
-
-
11
if @term.blank?
-
2
render json: { error: "No search term provided" }, status: :bad_request
-
2
return
-
end
-
-
9
if current_user.present?
-
8
@school = current_user.school
-
8
@class_division_id = current_user.class_division&.id
-
-
8
case current_user.role.name
-
when 'School Admin', 'Teacher'
-
5
search_for_teacher_or_admin
-
when 'Student'
-
2
search_for_student
-
else
-
1
render json: { message: 'Invalid User Type!' }, status: :unprocessable_entity
-
end
-
else
-
1
render json: { message: 'User Not Found!' }, status: :not_found
-
end
-
rescue => e
-
4
render json: { error: e.message }, status: :internal_server_error
-
end
-
-
1
private
-
-
1
def search_for_teacher_or_admin
-
5
@ebooks = search_ebooks.result
-
5
@accounts = search_accounts.result
-
5
@assignments = search_assignments_for_school_and_teacher.result
-
-
4
render_search_results
-
end
-
-
1
def search_for_student
-
2
@ebooks = search_ebooks.result
-
2
@accounts = search_accounts.result
-
2
@assignments = search_assignments_for_students.result
-
-
2
render_search_results
-
end
-
-
1
def render_search_results
-
6
if @ebooks.present? && @accounts.present? && @assignments.present?
-
render json: { ebooks: serialize_ebooks(@ebooks), accounts: serialize_accounts(@accounts), assignments: serialize_assignments(@assignments) }, status: :ok
-
6
elsif @ebooks.present? && @accounts.present?
-
render json: { ebooks: serialize_ebooks(@ebooks), accounts: serialize_accounts(@accounts) }, status: :ok
-
6
elsif @ebooks.present? && @assignments.present?
-
render json: { ebooks: serialize_ebooks(@ebooks), assignments: serialize_assignments(@assignments) }, status: :ok
-
6
elsif @accounts.present? && @assignments.present?
-
render json: { accounts: serialize_accounts(@accounts), assignments: serialize_assignments(@assignments) }, status: :ok
-
6
elsif @ebooks.present?
-
1
render json: { ebooks: serialize_ebooks(@ebooks) }, status: :ok
-
5
elsif @accounts.present?
-
1
render json: { accounts: serialize_accounts(@accounts) }, status: :ok
-
4
elsif @assignments.present?
-
1
render json: { assignments: serialize_assignments(@assignments) }, status: :ok
-
else
-
3
render json: { message: "No results found for '#{@term}'. Please try a different search term." }, status: :not_found
-
end
-
end
-
-
1
def current_user
-
42
@account = find_account(@token&.id)
-
end
-
-
1
def find_account(account_id)
-
42
AccountBlock::Account.find_by(id: account_id)
-
rescue ActiveRecord::RecordNotFound
-
nil
-
end
-
-
1
def search_accounts
-
3
accounts = AccountBlock::Account.all.where(school_id: @school.id)
-
3
accounts.ransack(first_name_or_last_name_cont: @term)
-
end
-
-
1
def search_assignments_for_students
-
1
assignments = BxBlockCatalogue::Assignment.where(class_division_id: @class_division_id)
-
1
assignments.ransack(title_cont: @term)
-
end
-
-
1
def search_assignments_for_school_and_teacher
-
2
assignments = BxBlockCatalogue::Assignment.where(school_id: @school.id)
-
2
assignments.ransack(title_cont: @term)
-
end
-
-
1
def search_ebooks
-
3
BxBlockBulkUploading::Ebook.ransack(title_or_publisher_cont: @term)
-
end
-
-
1
def serialize_accounts(accounts)
-
1
AccountSerializer.new(accounts).serializable_hash
-
end
-
-
1
def serialize_ebooks(ebooks)
-
1
EbookSerializer.new(ebooks, serialization_options).serializable_hash
-
end
-
-
1
def serialize_assignments(assignments)
-
1
AssignmentSerializer.new(assignments).serializable_hash
-
end
-
-
-
1
def serialization_options
-
1
{ params: { host: request.protocol + request.host_with_port } }
-
end
-
end
-
end
-
module BxBlockFavourites
-
class ApplicationController < BuilderBase::ApplicationController
-
include BuilderJsonWebToken::JsonWebTokenValidation
-
-
before_action :validate_json_web_token
-
-
rescue_from ActiveRecord::RecordNotFound, with: :not_found
-
-
private
-
-
def not_found
-
render json: {"errors" => ["Record not found"]}, status: :not_found
-
end
-
-
def current_user
-
@current_user ||= AccountBlock::Account.find(@token.id) if @token.present?
-
end
-
end
-
end
-
module BxBlockFavourites
-
class FavouritesController < ApplicationController
-
def index
-
favourites = BxBlockFavourites::Favourite.where(user_id: current_user.id)
-
if params[:favouriteable_type]
-
favourites = favourites.where(favouriteable_type: params[:favouriteable_type])
-
end
-
-
if favourites.present?
-
serializer = BxBlockFavourites::FavouriteSerializer.new(favourites)
-
render json: serializer.serializable_hash,
-
status: :ok
-
else
-
render json: {
-
errors: 'Favourites not found'
-
}, status: :not_found
-
end
-
end
-
-
def create
-
favourite = BxBlockFavourites::Favourite.new(
-
favourites_params.merge({user_id: current_user.id})
-
)
-
if favourite.save
-
serializer = BxBlockFavourites::FavouriteSerializer.new(favourite)
-
render json: serializer.serializable_hash,
-
status: :ok
-
else
-
render json: {errors: favourite.errors},
-
status: :unprocessable_entity
-
end
-
rescue => e
-
render json: {errors: e.message},
-
status: :unprocessable_entity
-
end
-
-
def destroy
-
favourite =
-
BxBlockFavourites::Favourite.find(params[:id])
-
if favourite.destroy
-
render json: {message: "Destroy successfully"},
-
status: :ok
-
end
-
end
-
-
private
-
-
def favourites_params
-
params.require(:data).permit \
-
:favouriteable_id, :favouriteable_type
-
end
-
end
-
end
-
module BxBlockFedexIntegration
-
class ApplicationController < BuilderBase::ApplicationController
-
include BuilderJsonWebToken::JsonWebTokenValidation
-
-
before_action :validate_json_web_token
-
-
rescue_from ActiveRecord::RecordNotFound, :with => :not_found
-
-
private
-
-
def not_found
-
render :json => {'errors' => ['Record not found']}, :status => :not_found
-
end
-
end
-
end
-
module BxBlockFedexIntegration
-
class ShipmentsController < ApplicationController
-
def create
-
shipment_params = jsonapi_deserialize(params)
-
create_shipment = CreateShipment.new(shipment_params)
-
-
if create_shipment.save
-
render json: { shipment: CreateShipmentSerializer.new(create_shipment).serializable_hash }, status: :created
-
else
-
render json: response, status: :unprocessable_entity
-
end
-
end
-
-
def show
-
shipment = CreateShipment.find(params[:id])
-
-
if shipment.present?
-
render json: { shipment: CreateShipmentSerializer.new(shipment).serializable_hash }, status: :ok
-
else
-
render json: shipment, status: :not_found
-
end
-
end
-
end
-
end
-
module BxBlockForgotPassword
-
class ApplicationController < BuilderBase::ApplicationController
-
# protect_from_forgery with: :exception
-
end
-
end
-
module BxBlockForgotPassword
-
class OtpConfirmationsController < ApplicationController
-
def create
-
if create_params[:token].present? && create_params[:otp_code].present?
-
# Try to decode token with OTP information
-
begin
-
token = BuilderJsonWebToken.decode(create_params[:token])
-
rescue JWT::ExpiredSignature
-
return render json: {
-
errors: [{
-
pin: 'OTP has expired, please request a new one.',
-
}],
-
}, status: :unauthorized
-
rescue JWT::DecodeError => e
-
return render json: {
-
errors: [{
-
token: 'Invalid token',
-
}],
-
}, status: :bad_request
-
end
-
-
# Try to get OTP object from token
-
begin
-
otp = token.type.constantize.find(token.id)
-
rescue ActiveRecord::RecordNotFound => e
-
return render json: {
-
errors: [{
-
otp: 'Token invalid',
-
}],
-
}, status: :unprocessable_entity
-
end
-
-
# Check OTP code
-
if otp.pin == create_params[:otp_code].to_i
-
otp.activated = true
-
otp.save
-
render json: {
-
messages: [{
-
otp: 'OTP validation success',
-
}],
-
}, status: :created
-
else
-
return render json: {
-
errors: [{
-
otp: 'Invalid OTP code',
-
}],
-
}, status: :unprocessable_entity
-
end
-
else
-
return render json: {
-
errors: [{
-
otp: 'Token and OTP code are required',
-
}],
-
}, status: :unprocessable_entity
-
end
-
end
-
-
private
-
-
def create_params
-
params.require(:data)
-
.permit(*[
-
:email,
-
:full_phone_number,
-
:token,
-
:otp_code,
-
:new_password,
-
])
-
end
-
end
-
end
-
module BxBlockForgotPassword
-
class OtpsController < ApplicationController
-
def create
-
puts " - params = #{params}"
-
# Check what type of account we are trying to recover
-
json_params = jsonapi_deserialize(params)
-
if json_params['email'].present?
-
# Get account by email
-
account = AccountBlock::EmailAccount
-
.where(
-
"LOWER(email) = ? AND activated = ?",
-
json_params['email'].downcase,
-
true
-
).first
-
return render json: {
-
errors: [{
-
otp: 'Account not found',
-
}],
-
}, status: :not_found if account.nil?
-
-
email_otp = AccountBlock::EmailOtp.new(jsonapi_deserialize(params))
-
if email_otp.save
-
send_email_for email_otp
-
render json: serialized_email_otp(email_otp, account.id),
-
status: :created
-
else
-
render json: {
-
errors: [email_otp.errors],
-
}, status: :unprocessable_entity
-
end
-
elsif json_params['full_phone_number'].present?
-
# Get account by phone number
-
phone = Phonelib.parse(json_params['full_phone_number']).sanitized
-
account = AccountBlock::SmsAccount.find_by(
-
full_phone_number: phone,
-
activated: true
-
)
-
return render json: {
-
errors: [{
-
otp: 'Account not found',
-
}],
-
}, status: :not_found if account.nil?
-
-
sms_otp = AccountBlock::SmsOtp.new(jsonapi_deserialize(params))
-
if sms_otp.save
-
render json: serialized_sms_otp(sms_otp, account.id), status: :created
-
else
-
render json: {
-
errors: [sms_otp.errors],
-
}, status: :unprocessable_entity
-
end
-
else
-
return render json: {
-
errors: [{
-
otp: 'Email or phone number required',
-
}],
-
}, status: :unprocessable_entity
-
end
-
end
-
-
private
-
-
def send_email_for(otp_record)
-
EmailOtpMailer
-
.with(otp: otp_record, host: request.base_url)
-
.otp_email.deliver
-
end
-
-
def serialized_email_otp(email_otp, account_id)
-
token = token_for(email_otp, account_id)
-
EmailOtpSerializer.new(
-
email_otp,
-
meta: { token: token }
-
).serializable_hash
-
end
-
-
def serialized_sms_otp(sms_otp, account_id)
-
token = token_for(sms_otp, account_id)
-
SmsOtpSerializer.new(
-
sms_otp,
-
meta: { token: token }
-
).serializable_hash
-
end
-
-
def token_for(otp_record, account_id)
-
BuilderJsonWebToken.encode(
-
otp_record.id,
-
5.minutes.from_now,
-
type: otp_record.class,
-
account_id: account_id
-
)
-
end
-
end
-
end
-
module BxBlockForgotPassword
-
class PasswordsController < ApplicationController
-
def create
-
if create_params[:token].present? && create_params[:new_password].present?
-
# Try to decode token with OTP information
-
begin
-
token = BuilderJsonWebToken.decode(create_params[:token])
-
rescue JWT::DecodeError => e
-
return render json: {
-
errors: [{
-
token: 'Invalid token',
-
}],
-
}, status: :bad_request
-
end
-
-
# Try to get OTP object from token
-
begin
-
otp = token.type.constantize.find(token.id)
-
rescue ActiveRecord::RecordNotFound => e
-
return render json: {
-
errors: [{
-
otp: 'Token invalid',
-
}],
-
}, status: :unprocessable_entity
-
end
-
-
# Check if OTP was validated
-
unless otp.activated?
-
return render json: {
-
errors: [{
-
otp: 'OTP code not validated',
-
}],
-
}, status: :unprocessable_entity
-
else
-
# Check new password requirements
-
password_validation = AccountBlock::PasswordValidation
-
.new(create_params[:new_password])
-
-
is_valid = password_validation.valid?
-
error_message = password_validation.errors.full_messages.first
-
-
unless is_valid
-
return render json: {
-
errors: [{
-
password: error_message,
-
}],
-
}, status: :unprocessable_entity
-
else
-
# Update account with new password
-
account = AccountBlock::Account.find(token.account_id)
-
-
if account.update(:password => create_params[:new_password])
-
# Delete OTP object as it's not needed anymore
-
otp.destroy
-
-
serializer = AccountBlock::AccountSerializer.new(account)
-
serialized_account = serializer.serializable_hash
-
-
render json: serialized_account, status: :created
-
else
-
render json: {
-
errors: [{
-
profile: 'Password change failed',
-
}],
-
}, status: :unprocessable_entity
-
end
-
end
-
end
-
else
-
return render json: {
-
errors: [{
-
otp: 'Token and new password are required',
-
}],
-
}, status: :unprocessable_entity
-
end
-
end
-
-
private
-
-
def create_params
-
params.require(:data)
-
.permit(*[
-
:email,
-
:full_phone_number,
-
:token,
-
:otp_code,
-
:new_password,
-
])
-
end
-
end
-
end
-
module BxBlockInvoice
-
class ApplicationController < BuilderBase::ApplicationController
-
include BuilderJsonWebToken::JsonWebTokenValidation
-
-
before_action :validate_json_web_token
-
-
rescue_from ActiveRecord::RecordNotFound, with: :not_found
-
-
private
-
-
def not_found
-
render json: {"errors" => ["Record not found"]}, status: :not_found
-
end
-
end
-
end
-
module BxBlockInvoice
-
class InvoiceController < BxBlockInvoice::ApplicationController
-
skip_before_action :validate_json_web_token, only: [:invoice_pdf, :generate_invoice_pdf]
-
before_action :fetch_invoice, only: %i[generate_invoice_pdf invoice_pdf]
-
-
def generate_invoice_pdf
-
host = "#{request.protocol}#{request.host_with_port}"
-
-
render json: {invoice: "#{host}/#{Rails.application.routes.url_helpers.rails_blob_path(@invoice.invoice_pdf,
-
only_path: true)}"}
-
end
-
-
private
-
-
def fetch_invoice
-
@invoice = Invoice.find_by(invoice_number: params[:invoice_number].to_s)
-
return render json: {errors: [{message: "No invoice found."}]}, status: :not_found unless @invoice
-
end
-
end
-
end
-
1
module BxBlockLandingpage2
-
1
class ApplicationController < BuilderBase::ApplicationController
-
1
include BuilderJsonWebToken::JsonWebTokenValidation
-
-
1
before_action :validate_json_web_token
-
-
1
rescue_from ActiveRecord::RecordNotFound, :with => :not_found
-
-
1
private
-
-
1
def not_found
-
render :json => {'errors' => ['Record not found']}, :status => :not_found
-
end
-
end
-
end
-
1
module BxBlockLandingpage2
-
1
class LandingpagesController < ApplicationController
-
1
before_action :validate_json_web_token, only: [:index, :student_find, :show_bundle, :show_ebooks, :show_one_book_details, :ebook_assign, :student_assigned_ebook_index, :student_assigned_assignment_index, :student_assigned_video_index, :list_subject, :class_listing, :division_listing]
-
1
before_action :authenticate_user_type, only: [:show_bundle, :show_ebooks]
-
-
1
def index
-
5
teacher_account = AccountBlock::Account.find_by(id: @token.id)
-
5
subject_managements = BxBlockCatalogue::SubjectManagement.where(account_id: teacher_account.id)
-
5
students = []
-
5
role = BxBlockRolesPermissions::Role.find_by(name: 'Student')
-
-
5
subject_managements.each do |subject_management|
-
5
class_division = subject_management.class_division
-
5
school = class_division.school_class.school
-
-
5
if class_division
-
5
student_accounts = class_division.accounts.where(role_id: role.id)
-
-
5
if params[:search_term].present?
-
2
search_term = params[:search_term].downcase
-
2
student_accounts = student_accounts
-
.where("lower(student_unique_id) LIKE ? OR lower(first_name) LIKE ?", "%#{search_term}%", "%#{search_term}%")
-
end
-
-
5
if params[:class_number].present?
-
1
school_class = school.school_classes&.find_by(class_number: params[:class_number])
-
1
student_accounts = student_accounts&.where(school_class_id: school_class&.id)
-
end
-
-
5
if params[:class_division].present? && school_class.present?
-
1
class_division = school_class.class_divisions&.find_by(division_name: params[:class_division])
-
1
student_accounts = student_accounts&.where(class_division_id: class_division&.id)
-
end
-
-
5
students += student_accounts.to_a if student_accounts.present?
-
end
-
end
-
-
5
if students.present?
-
4
paginated_students = Kaminari.paginate_array(students.uniq).page(params[:page]).per(params[:per_page])
-
4
count = students.count
-
4
landingpage_serializer = BxBlockLandingpage2::LandingpageSerializer.new(paginated_students, serialization_options)
-
4
render json: landingpage_serializer.serializable_hash.merge(meta: { count: count })
-
else
-
1
render json: { error: 'No students found' }, status: :not_found
-
end
-
end
-
-
1
def student_find
-
2
@student = AccountBlock::Account.find_by(id: params[:id])
-
-
2
if @student.present?
-
1
render json: BxBlockLandingpage2::LandingpageSerializer.new(@student, serialization_options)
-
else
-
1
render json: { error: 'No student found with the given ID and class division' }, status: :unprocessable_entity
-
end
-
end
-
-
1
def student_assigned_assignment_index
-
2
student = AccountBlock::Account.find(params[:id])
-
2
classdivision = student.class_division
-
2
subject_managements = classdivision.subject_managements
-
2
ids = subject_managements.pluck(:id)
-
2
subject_filter = params[:subject]
-
-
2
if subject_filter.present?
-
1
subject_id = BxBlockCatalogue::Subject.find_by(subject_name: subject_filter)&.id
-
1
ids = subject_managements.where(subject_id: subject_id).pluck(:id) if subject_id
-
end
-
-
2
assignments = BxBlockCatalogue::Assignment.where(subject_management_id: ids)
-
2
paginated_assignments = assignments.page(params[:page]).per(params[:per_page])
-
-
2
assignments_data = paginated_assignments.map do |assignment|
-
{
-
assignment_title: assignment.title,
-
subject_name: assignment.subject_management.subject.subject_name,
-
# date_assigned: assignment.created_at
-
date_assigned: assignment.created_at.strftime("%-d %b %Y")
-
}
-
end
-
2
render json: { assignments: assignments_data, count: assignments.uniq.count }, status: :ok
-
end
-
-
1
def student_assigned_video_index
-
3
student = AccountBlock::Account.find(params[:id])
-
3
classdivision = student.class_division
-
3
subject_managements = classdivision.subject_managements
-
3
ids = subject_managements.pluck(:id)
-
3
subject_filter = params[:subject]
-
-
3
if subject_filter.present?
-
2
subject_id = BxBlockCatalogue::Subject.find_by(subject_name: subject_filter)&.id
-
2
ids &= subject_managements.where(subject_id: subject_id).pluck(:id) if subject_id
-
end
-
-
3
videos_lectures = BxBlockCatalogue::VideosLecture.where(subject_management_id: ids)
-
3
paginated_videos = videos_lectures.page(params[:page]).per(params[:per_page])
-
-
3
videos_data = paginated_videos.map do |video|
-
{
-
video_title: video.title,
-
subject_name: video.subject_management.subject.subject_name,
-
date_assigned: video.created_at
-
}
-
end
-
-
3
render json: { videos_data: videos_data, count: videos_lectures.count }, status: :ok
-
end
-
-
1
def show_bundle
-
2
@collections = BxBlockBulkUploading::BundleManagement.all
-
-
2
if @collections.present?
-
1
render json: BxBlockBulkUploading::BundleManagementSerializer.new(@collections,serialization_options).serializable_hash, status: :ok
-
else
-
1
render json: { error: 'Empty' }, status: :unprocessable_entity
-
end
-
end
-
-
1
def show_ebooks
-
2
@collections = BxBlockBulkUploading::Ebook.all
-
-
2
if params[:subject].present?
-
2
@collections = @collections.where(subject: params[:subject])
-
end
-
-
2
if params[:search_term].present?
-
2
search_term = params[:search_term].downcase
-
3
@collections = @collections.select { |ebook| ebook.title.downcase.include?(search_term) || ebook.author.downcase.include?(search_term) }
-
end
-
-
2
if @collections.any?
-
1
render json: BxBlockBulkUploading::EbookSerializer.new(@collections, serialization_options).serializable_hash, status: :ok
-
else
-
1
render json: { error: 'No matching books found.' }, status: :not_found
-
end
-
end
-
-
1
def show_one_book_details
-
1
@ebook = BxBlockBulkUploading::Ebook.find(params[:id])
-
-
1
if @ebook.present?
-
1
render json: BxBlockBulkUploading::EbookSerializer.new(@ebook, serialization_options).serializable_hash, status: :ok
-
end
-
end
-
-
1
def student_assigned_ebook_index
-
2
student = AccountBlock::Account.find_by(id: params[:id])
-
2
student_ebooks = BxBlockBulkUploading::EbookAllotment.where(student_id: params[:id])
-
-
2
if params[:subject].present?
-
1
student_ebooks = student_ebooks.joins(:ebook).where(bx_block_bulk_uploading_ebooks: { subject: params[:subject] })
-
end
-
-
2
stud_ebooks = student_ebooks.uniq.map(&:ebook)
-
2
stud_ebooks.uniq!(&:id)
-
2
paginated_ebook = Kaminari.paginate_array(stud_ebooks).page(params[:page]).per(params[:per_page])
-
-
2
alloted_ebooks_details = paginated_ebook.map do |ebook|
-
{
-
3
title: ebook.title,
-
subject: ebook.subject,
-
allotted_date: ebook.ebook_allotments.find_by(student_id: student.id)&.alloted_date
-
}
-
end
-
-
2
total_count = stud_ebooks.count
-
2
render json: { ebooks: alloted_ebooks_details, total_assigned_ebook: total_count }, status: :ok
-
end
-
-
1
def list_subject
-
2
subjects = BxBlockCatalogue::Subject.all
-
-
2
if subjects.present?
-
3
subjects_data = subjects.map { |subject| { id: subject.id, name: subject.subject_name } }
-
1
render json: { subjects: subjects_data }, status: :ok
-
else
-
1
render json: { error: 'Subject Not found.' }, status: :not_found
-
end
-
end
-
-
1
def class_listing
-
2
account = AccountBlock::Account.find_by(id: @token.id)
-
2
school = account.school
-
2
school_classes = school.school_classes.select(:id, :class_number)
-
2
if school_classes.present?
-
1
render json: { school_classes: school_classes }, status: :ok
-
else
-
1
render json: { error: 'Class Not found.' }, status: :not_found
-
end
-
end
-
-
1
def division_listing
-
1
account = AccountBlock::Account.find_by(id: @token.id)
-
1
school = account.school
-
1
classes = school.school_classes.includes(:class_divisions)
-
1
all_divisions = []
-
1
classes.each do |classroom|
-
1
all_divisions.concat(classroom.class_divisions.select(:id, :division_name))
-
end
-
1
unique_divisions = all_divisions.uniq(&:division_name)
-
1
render json: { divisions: unique_divisions }, status: :ok
-
end
-
-
-
1
private
-
-
1
def serialization_options
-
8
{ params: { host: request.protocol + request.host_with_port } }
-
end
-
-
1
def authenticate_user_type
-
5
acc = AccountBlock::Account.find_by(id: @token.id)
-
5
name = acc&.role&.name
-
5
allowed_user_types = ['Student', 'Teacher', 'School Admin']
-
-
5
unless allowed_user_types.include?(name)
-
1
head :unauthorized
-
return
-
end
-
end
-
end
-
end
-
1
module BxBlockLandingpage2
-
1
class SchoolAdminLandingpagesController < ApplicationController
-
1
before_action :validate_json_web_token, :current_user
-
-
1
def get_users
-
begin
-
6
search_name = params[:search_name]&.downcase
-
6
database_type = params[:database_type]
-
6
class_number = params[:class_number]
-
6
class_division_name = params[:class_division_name]
-
6
filter_subject = params[:filter_subject]
-
-
6
if current_user.present? && current_user.role.name == "School Admin"
-
4
@school = current_user.school
-
4
@available_classes = fetch_classes
-
4
@class_division = fetch_class_divisions
-
4
@class_array = BxBlockCategories::SchoolClass.where(school_id: @school.id).pluck(:class_number).uniq.sort
-
4
@division_array = BxBlockCategories::ClassDivision.where(school_id: @school.id).pluck(:division_name).uniq.sort
-
-
8
selected_class = @available_classes.find { |c| c[:class_number] == class_number.to_i }
-
4
class_id = selected_class[:id] if selected_class.present?
-
4
selected_division = @class_division.find { |d| d[:division_name] == class_division_name }
-
4
class_division_id = selected_division[:id] if selected_division.present?
-
4
@all_students = fetch_accounts("Student", search_name, class_id, class_division_id)
-
4
@total_students_count = @all_students.total_count
-
4
@all_teachers = fetch_accounts("Teacher", search_name, class_id, class_division_id)
-
4
@total_teachers_count = @all_teachers.total_count
-
4
@ebooks = search_ebook(search_name, class_number, filter_subject)#.page(params[:page]).per(params[:per_page])
-
4
@total_ebooks_count = @ebooks.total_count
-
-
4
render_response(database_type)
-
else
-
2
render json: { message: "Invalid User!" }, status: :unprocessable_entity
-
end
-
rescue StandardError => e
-
render json: { message: "Internal Server Error: #{e.message}" }, status: :internal_server_error
-
end
-
end
-
-
1
def show_student_detail
-
8
content_type = params[:content_type]
-
8
search_name = params[:search_name]&.downcase
-
8
class_number = params[:class_number]
-
8
filter_subject = params[:filter_subject]
-
-
8
if school_admin?
-
7
school = current_user.school
-
7
@account = find_account(params[:id])
-
7
if @account.present?
-
12
@subjects_array = BxBlockCatalogue::Subject.all.map { |c| { id: c.id, subject_name: c.subject_name } }
-
# subject = BxBlockCatalogue::Subject.find_by(subject_name: filter_subject)
-
# subject_id = subject&.id
-
# subject_teacher_ids = @account.class_division.subject_teacher_ids
-
6
class_division_id = @account.class_division&.id
-
6
@video_lectures = get_videos(class_division_id, filter_subject).page(params[:page]).per(params[:per_page])
-
6
@total_video_count = @video_lectures.total_count
-
6
@assignments = get_assignments(class_division_id, filter_subject).page(params[:page]).per(params[:per_page])
-
6
@total_assignment_count = @assignments.total_count
-
6
@teachers = find_teachers(class_division_id, filter_subject)
-
6
@total_teacher_count = @teachers.total_count
-
6
@total_ebooks = search_ebook(search_name, class_number, filter_subject).page(params[:page]).per(params[:per_page])
-
6
@total_ebook_count = @total_ebooks.total_count
-
-
6
render_response_for_student(content_type)
-
else
-
1
render json: { message: "User not found" }, status: :not_found
-
end
-
else
-
1
render_invalid_user_response
-
end
-
end
-
-
1
def show_teacher_detail
-
6
type = params[:type]
-
6
search_name = params[:search_name]&.downcase
-
6
class_number = params[:class_number]
-
6
filter_subject = params[:filter_subject]
-
begin
-
6
if school_admin?
-
4
school = current_user.school
-
4
@teacher = find_account(params[:id])
-
4
@teacher_allocated = BxBlockCategories::ClassDivision.where(account_id: params[:id] )
-
4
subjects = @teacher&.subject_ids
-
4
@subjects_data = BxBlockCatalogue::SubjectManagement.where(subject_id: subjects, account_id: @teacher&.id).page(params[:page]).per(params[:per_page])
-
4
@total_ebook = search_ebook(search_name, class_number, filter_subject)#.page(params[:page]).per(params[:per_page])
-
4
@ebooks_count = @total_ebook.total_count
-
8
@subjects = BxBlockCatalogue::Subject.all.map { |c| { id: c.id, subject_name: c.subject_name } }
-
-
4
render_response_for_teacher(type)
-
else
-
1
render_invalid_user_response
-
end
-
1
rescue ActiveRecord::RecordNotFound => e
-
render json: { message: "User not found: #{e.message}" }, status: :not_found
-
rescue StandardError => e
-
1
render json: { message: "Internal Server Error: #{e.message}" }, status: :internal_server_error
-
end
-
end
-
-
1
private
-
-
1
def render_response(database_type)
-
4
case database_type
-
when 'Teacher'
-
1
render json: { teacher_database: serialize_accounts(@all_teachers), teachers_count: @total_teachers_count }
-
when 'Student'
-
1
render json: { student_database: serialize_accounts(@all_students), students_count: @total_students_count }
-
when 'Publisher'
-
1
render json: { publisher_database: serialize_ebooks(@ebooks), ebooks_count: @total_ebooks_count }
-
else
-
1
render json: { student_database: serialize_accounts(@all_students), students_count: @total_students_count, teacher_database: serialize_accounts(@all_teachers), teachers_count: @total_teachers_count, publisher_database: serialize_ebooks(@ebooks), ebooks_count: @total_ebooks_count, class_array: @class_array, division_array: @division_array }, status: :ok
-
end
-
end
-
-
1
def render_response_for_student(content_type)
-
6
case content_type
-
when 'Student'
-
1
render json: { student: serialize_account(@account) }, status: :ok
-
when 'Teacher'
-
1
render json: { teachers: serialize_allocated(@teachers), total_teachers: @total_teacher_count }, status: :ok
-
when 'Video'
-
1
render json: { videos: serialize_videos(@video_lectures), videos_count: @total_video_count }, status: :ok
-
when 'Ebook'
-
1
render json: { ebooks: serialize_ebooks(@total_ebooks), total_ebooks: @total_ebook_count }, status: :ok
-
when 'Assignment'
-
1
render json: { assignments: serialize_assignments(@assignments), assignments_count: @total_assignment_count }, status: :ok
-
else
-
1
render json: { student: serialize_account(@account), teachers: serialize_allocated(@teachers), total_teachers: @total_teacher_count, ebooks: serialize_ebooks(@total_ebooks), total_ebooks: @total_ebook_count,assignments_count: @total_assignment_count, videos_count: @total_video_count, subjects: @subjects_array }, status: :ok
-
end
-
end
-
-
1
def render_response_for_teacher(type)
-
4
case type
-
when 'Teacher'
-
1
render json: { teacher: serialize_account(@teacher) }, status: :ok
-
when 'Allocation'
-
1
render json: { allocations: serialize_allocation(@subjects_data) }, status: :ok
-
when 'Ebook'
-
1
render json: { ebooks: serialize_ebooks(@total_ebook), total_ebooks: @ebooks_count }, status: :ok
-
else
-
1
render json: { teacher: serialize_account(@teacher), teacher_allocations: serialize_allocation(@subjects_data), ebooks: serialize_ebooks(@total_ebook), total_ebooks: @ebooks_count, subjects: @subjects }, status: :ok
-
end
-
end
-
-
1
def current_user
-
60
@account = find_account(@token&.id)
-
end
-
-
1
def school_admin?
-
14
current_user.role.name == "School Admin"
-
end
-
-
1
def render_invalid_user_response
-
2
render json: { message: "Invalid User Type!" }, status: :unprocessable_entity
-
end
-
-
1
def fetch_classes
-
8
BxBlockCategories::SchoolClass.where(school_id: @school.id).map { |c| { id: c.id, class_number: c.class_number } }
-
end
-
-
1
def fetch_class_divisions
-
4
BxBlockCategories::ClassDivision.where(school_id: @school.id).map { |c| { id: c.id, division_name: c.division_name } }
-
end
-
-
1
def fetch_accounts(role_name, search_name, class_id, class_division_id)
-
8
accounts = BxBlockRolesPermissions::Role.find_by(name: role_name).accounts.where(school_id: @school.id)
-
8
accounts = accounts.where(school_class_id: class_id) if class_id.present?
-
8
accounts = accounts.where(school_class_id: class_id, class_division_id: class_division_id) if class_division_id.present?
-
8
accounts = accounts.where("LOWER(first_name) LIKE ? OR LOWER(student_unique_id) LIKE ? OR LOWER(teacher_unique_id) LIKE ?", "%#{search_name}%", "%#{search_name}%", "%#{search_name}%") if search_name.present?
-
8
accounts.page(params[:page]).per(params[:per_page])
-
end
-
-
1
def find_account(account_id)
-
71
AccountBlock::Account.find_by(id: account_id)
-
rescue ActiveRecord::RecordNotFound
-
nil
-
end
-
-
1
def find_teachers(division_id, subject_name)
-
6
teachers = BxBlockCatalogue::SubjectManagement.where(class_division_id: division_id)
-
6
if subject_name.present?
-
2
subject = BxBlockCatalogue::Subject.find_by(subject_name: subject_name)
-
2
subject_id = subject&.id
-
2
teachers = BxBlockCatalogue::SubjectManagement.where(subject_id: subject_id, class_division_id: division_id)
-
end
-
6
teachers.page(params[:page]).per(params[:per_page])
-
end
-
-
1
def search_ebook(search_name, class_id, subject)
-
14
ebooks = BxBlockBulkUploading::Ebook.all
-
14
ebooks = ebooks.where(school_class_id: class_id) if class_id.present?
-
14
ebooks = ebooks.where(subject: subject) if subject.present?
-
14
ebooks = ebooks.where("LOWER(title) LIKE ? OR LOWER(publisher) LIKE ?", "%#{search_name}%", "%#{search_name}%") if search_name.present?
-
14
ebooks.page(params[:page]).per(params[:per_page])
-
end
-
-
1
def get_videos(class_division_id, subject_name)
-
6
video_lectures = BxBlockCatalogue::VideosLecture.where(class_division_id: class_division_id) if class_division_id.present?
-
6
if subject_name.present?
-
2
subject = BxBlockCatalogue::Subject.find_by(subject_name: subject_name)
-
2
video_lectures = video_lectures.where(subject_id: subject&.id)
-
end
-
6
video_lectures.page(params[:page]).per(params[:per_page])
-
end
-
-
1
def get_assignments(class_division_id, subject_name)
-
6
assignments = BxBlockCatalogue::Assignment.where(class_division_id: class_division_id) if class_division_id.present?
-
6
if subject_name.present?
-
2
subject = BxBlockCatalogue::Subject.find_by(subject_name: subject_name)
-
2
assignments = assignments.where(subject_id: subject&.id)
-
end
-
6
assignments.page(params[:page]).per(params[:per_page])
-
end
-
-
1
def serialize_accounts(accounts)
-
4
AccountSerializer.new(accounts, serialization_options).serializable_hash
-
end
-
-
1
def serialize_account(account)
-
4
AccountSerializer.new(account, serialization_options).serializable_hash
-
end
-
-
1
def serialize_allocation(subjects_data)
-
2
TeacherAllocationSerializer.new(subjects_data, serialization_options).serializable_hash
-
end
-
-
1
def serialize_allocated(teachers)
-
2
TeacherAllocatedSerializer.new(teachers, serialization_options).serializable_hash
-
end
-
-
1
def serialize_ebooks(ebooks)
-
6
EbookSerializer.new(ebooks, serialization_options).serializable_hash
-
end
-
-
1
def serialize_videos(videos)
-
1
VideoSerializer.new(videos, serialization_options).serializable_hash
-
end
-
-
1
def serialize_assignments(assignments)
-
1
AssignmentSerializer.new(assignments, serialization_options).serializable_hash
-
end
-
-
1
def serialization_options
-
20
{ params: { host: request.protocol + request.host_with_port } }
-
end
-
end
-
end
-
1
module BxBlockLandingpage2
-
1
class StudentLandingpagesController < ApplicationController
-
1
before_action :validate_json_web_token, only: [:assigned_assignment_index,:ebook_show_all, :hide_ebook]
-
-
1
def ebook_show_all
-
3
student = AccountBlock::Account.find_by(id: @token.id)
-
3
class_id = student&.class_division&.school_class&.class_number
-
3
@books = BxBlockBulkUploading::Ebook.where(school_class_id: class_id)
-
-
3
if params[:subject].present?
-
2
@books = @books.where(subject: params[:subject])
-
end
-
-
3
if params[:search_term].present?
-
1
search_term = params[:search_term].downcase
-
1
@books = @books.where("LOWER(title) LIKE ? OR LOWER(author) LIKE ?", "%#{search_term}%", "%#{search_term}%")
-
end
-
-
3
hidden_ebook_ids = BxBlockBulkUploading::RemoveBook.where(account_id: student.id).pluck(:ebook_id)
-
3
@books = @books.where.not(id: hidden_ebook_ids)
-
-
3
@books = @books.page(params[:page]).per(params[:per_page])
-
3
total_count = @books.total_count
-
3
if @books.present?
-
1
student_landingpage_serializer = BxBlockBulkUploading::EbookSerializer.new(@books, serialization_options)
-
1
render json: student_landingpage_serializer.serializable_hash.merge(meta: { count: total_count }), status: :ok
-
else
-
2
render json: { error: 'No book found.' }, status: :not_found
-
end
-
end
-
-
1
def hide_ebook
-
2
student = AccountBlock::Account.find_by(id: @token.id)
-
2
ebook = BxBlockBulkUploading::Ebook.find_by(id: params[:ebook_id])
-
-
2
if student && ebook
-
-
2
if params[:pin].present? && authenticate_pin(params[:pin])
-
1
BxBlockBulkUploading::RemoveBook.create(account_id: student.id, ebook_id: ebook.id)
-
1
render json: { success: 'Ebook delete successfully.' }, status: :ok
-
else
-
1
render json: { error: 'Invalid PIN. Please provide a valid PIN to delete the ebook.' }, status: :unprocessable_entity
-
end
-
-
end
-
end
-
-
1
def assigned_assignment_index
-
5
student = AccountBlock::Account.find_by(id: @token.id)
-
5
classdivision = student.class_division
-
5
subject_managements = classdivision.subject_managements
-
5
ids = subject_managements.pluck(:id)
-
5
subject_filter = params[:subject]
-
-
5
if subject_filter.present?
-
2
subject_id = BxBlockCatalogue::Subject.find_by(subject_name: subject_filter)&.id
-
2
if subject_id
-
1
ids = subject_managements.where(subject_id: subject_id).pluck(:id)
-
else
-
1
render json: { error: 'no assignment found.' }, status: :not_found
-
1
return
-
end
-
end
-
-
4
assignments = BxBlockCatalogue::Assignment.where(subject_management_id: ids)
-
-
4
assignment_title_filter = params[:assignment_title]
-
4
if assignment_title_filter.present?
-
2
assignment_title_filter = params[:assignment_title].downcase
-
2
assignments = assignments.where("LOWER(title) LIKE ?", "%#{assignment_title_filter}%")
-
end
-
-
4
paginated_assignments = assignments.page(params[:page]).per(params[:per_page])
-
-
4
assignments_data = paginated_assignments.map do |assignment|
-
2
teacher = AccountBlock::Account.find_by(id: assignment.account_id)
-
{
-
2
assignment_title: assignment.title,
-
subject_name: assignment.subject_management.subject.subject_name,
-
assigned_by: teacher&.first_name
-
}
-
end
-
4
if assignments_data.present?
-
2
render json: { assignments: assignments_data, count: assignments_data.count }, status: :ok
-
else
-
2
render json: { error: 'No assignment found.' }, status: :not_found
-
end
-
end
-
-
1
private
-
-
1
def authenticate_pin(pin)
-
2
student = AccountBlock::Account.find_by(id: @token.id)
-
2
pin == student.pin
-
end
-
-
1
def serialization_options
-
1
{ params: { host: request.protocol + request.host_with_port } }
-
end
-
-
end
-
end
-
module BxBlockLanguageOptions
-
class ApplicationController < BuilderBase::ApplicationController
-
include BuilderJsonWebToken::JsonWebTokenValidation
-
-
before_action :validate_json_web_token
-
-
rescue_from ActiveRecord::RecordNotFound, :with => :not_found
-
-
private
-
-
def not_found
-
render :json => {'errors' => ['Record not found']}, :status => :not_found
-
end
-
-
def current_user
-
return unless @token
-
@current_user ||= AccountBlock::Account.find(@token.id)
-
end
-
end
-
end
-
module BxBlockLanguageOptions
-
class LanguagesController < ApplicationController
-
skip_before_action :validate_json_web_token, only: [:index, :get_all_translations, :last_translation_time]
-
-
def index
-
case params[:type]
-
when 'content_languages'
-
languages = BxBlockLanguageOptions::Language.content_languages
-
when 'app_languages'
-
languages = BxBlockLanguageOptions::Language.app_languages
-
else
-
languages = BxBlockLanguageOptions::Language.all
-
end
-
serializer = LanguageSerializer.new(languages)
-
render json: serializer, status: :ok
-
end
-
-
def set_app_language
-
if current_user.update(app_language_id: params[:app_language_id])
-
serializer = LanguageSerializer.new(current_user.app_language)
-
serialized = serializer.serializable_hash
-
render :json => serialized
-
else
-
render :json => {:errors => current_user.errors,
-
:status => :unprocessable_entity}
-
end
-
end
-
-
def update
-
if current_user.update(language_ids: params[:languages_ids])
-
serializer = LanguageSerializer.new(current_user.languages)
-
serialized = serializer.serializable_hash
-
render :json => serialized
-
else
-
render :json => {:errors => current_user.errors,
-
:status => :unprocessable_entity}
-
end
-
end
-
-
def get_all_translations
-
application_messages = BxBlockLanguageOptions::ApplicationMessage.all.includes(:translations)
-
render json: SerializeTranslations.call(application_messages)
-
end
-
-
def last_translation_time
-
render json: {
-
last_transation_time: BxBlockLanguageOptions::ApplicationMessage.order(:updated_at).last&.updated_at
-
}
-
end
-
end
-
end
-
module BxBlockLike
-
class ApplicationController < BuilderBase::ApplicationController
-
include BuilderJsonWebToken::JsonWebTokenValidation
-
-
before_action :validate_json_web_token
-
before_action :check_account_activated
-
-
rescue_from ActiveRecord::RecordNotFound, with: :not_found
-
-
private
-
-
def not_found
-
render json: {
-
"errors" => [
-
"Record not found"
-
]
-
}, status: :not_found
-
end
-
-
def current_user
-
return if @token.blank?
-
@current_user ||= AccountBlock::Account.find(@token.id)
-
end
-
-
def check_account_activated
-
account = AccountBlock::Account.find_by(id: current_user.id)
-
unless account.activated
-
render json: {error: {
-
message: "Account has been not activated"
-
}}, status: :unprocessable_entity
-
end
-
end
-
end
-
end
-
module BxBlockLike
-
class LikesController < ApplicationController
-
def index
-
likes = if likeable_type
-
BxBlockLike::Like.where(
-
like_by_id: current_user.id,
-
likeable_type: likeable_type
-
)
-
else
-
BxBlockLike::Like.where(like_by_id: current_user.id)
-
end
-
-
if likes.present?
-
render json: BxBlockLike::LikeSerializer.new(likes).serializable_hash,
-
status: :ok
-
else
-
render json: {data: []}, status: :ok
-
end
-
end
-
-
def create
-
like = BxBlockLike::Like.find_or_initialize_by(
-
like_params.merge({like_by_id: current_user.id})
-
)
-
like.save
-
handle_create_response(like)
-
rescue => like
-
render json: {errors: [{like: like.message}]},
-
status: :unprocessable_entity
-
end
-
-
def destroy
-
like = BxBlockLike::Like.find_by(
-
id: params[:id], like_by_id: current_user.id
-
)
-
-
if like.present?
-
like.destroy
-
render json: {message: "Successfully destroy"},
-
status: :ok
-
else
-
render json: {message: "Not found"},
-
status: :not_found
-
end
-
end
-
-
private
-
-
def like_params
-
params.require(:data)[:attributes].permit \
-
:likeable_id, :likeable_type
-
end
-
-
def likeable_type
-
return if params[:like_type].blank?
-
(params[:like_type] == "profile") ?
-
["BxBlockProfile::Profile", "BxBlockProfile::CareerExperience",
-
"BxBlockProfile::Award", "BxBlockProfile::TestScoreAndCourse",
-
"BxBlockProfile::Course", "BxBlockProfile::EducationalQualification",
-
"BxBlockProfile::Project", "BxBlockComments::comment"] : "BxBlockPosts::Post"
-
end
-
-
def handle_create_response(like)
-
if like.persisted?
-
render json: BxBlockLike::LikeSerializer.new(like).serializable_hash,
-
status: :ok
-
else
-
render json: {errors: [{like: like.errors.full_messages}]},
-
status: :unprocessable_entity
-
end
-
end
-
end
-
end
-
module BxBlockLocation
-
class ApplicationController < BuilderBase::ApplicationController
-
include BuilderJsonWebToken::JsonWebTokenValidation
-
-
before_action :validate_json_web_token
-
-
rescue_from ActiveRecord::RecordNotFound, :with => :not_found
-
-
private
-
-
def not_found
-
render :json => {'errors' => ['Record not found']}, :status => :not_found
-
end
-
end
-
end
-
module BxBlockLocation
-
class VansController < ApplicationController
-
before_action :find_van, except: %i(near_vans estimated_arrival_time)
-
before_action :lat_lon, only: %i(near_vans)
-
-
COVERING_RADIOUS = 10
-
DEFAULT_VEHICLE_SPEED = 30 #in km/hr
-
-
def near_vans
-
vans_location = BxBlockLocation::Location.near(lat_lon, COVERING_RADIOUS, unit: :km)
-
vans_location.map(&:van)
-
vans = BxBlockLocation::Van.where(is_offline: false).joins(:location).where(
-
'locations.id = ?', vans_location.ids
-
)
-
vans_location = BxBlockLocation::Van.new.available_vans(vans)
-
render json: {
-
message: 'No van\'s present near your location'
-
} and return unless vans_location.present?
-
-
render json: BxBlockLocation::VanLocationSerializer.new(
-
vans_location,
-
params: {coordinates: lat_lon},
-
meta: {message: 'List of all near vans'}
-
), status: :ok
-
end
-
-
def estimated_arrival_time
-
service_provider = AccountBlock::Account.find(params[:service_provider_id])
-
render json: {
-
errors: 'Please select service provider'
-
} and return unless service_provider.present?
-
-
van_member = BxBlockLocation::VanMember.find_by_account_id(service_provider.id)
-
van = BxBlockLocation::Van.find_by_id(van_member.van_id)
-
-
address = BxBlockAddress::Address.find(params[:address_id])
-
render json: estimated_time_arrival_for(address, van.location)
-
end
-
-
def show
-
render json: BxBlockLocation::VanLocationSerializer.new(
-
@van.location,
-
meta: { message: 'Location of van' }
-
), status: :ok
-
end
-
-
def update
-
-
render json: BxBlockLocation::VanLocationSerializer.new(
-
@van.location,
-
meta: { message: 'Location updated successfully' }
-
), status: :ok and return if @van.location.update(van_params)
-
-
render json: { errors: 'Something goes wrong, location is not updated' }
-
end
-
-
private
-
-
def find_van
-
@van = BxBlockLocation::Van.find(params[:id])
-
end
-
-
def van_params
-
params.permit(:latitude, :longitude)
-
end
-
-
def lat_lon
-
render json: {
-
errors: 'Please send location'
-
} and return unless params[:latitude].present? and params[:longitude].present?
-
[params[:latitude], params[:longitude]]
-
end
-
-
def estimated_time_arrival_for address, van_location
-
distance = Geocoder::Calculations.distance_between(
-
address.to_coordinates, van_location.to_coordinates, units: :km
-
)
-
return {errors: 'Something went wrong'} unless distance.present?
-
estimated_time = distance / DEFAULT_VEHICLE_SPEED
-
{ estimated_time: estimated_time }
-
end
-
end
-
end
-
1
module BxBlockLogin
-
1
class ApplicationController < BuilderBase::ApplicationController
-
# protect_from_forgery with: :exception
-
end
-
end
-
1
module BxBlockLogin
-
1
class LoginsController < ApplicationController
-
1
def create
-
6
case params[:data][:type] #### rescue invalid API format
-
when 'Student', 'Teacher', 'School Admin', "Publisher"
-
5
account = OpenStruct.new(jsonapi_deserialize(params))
-
5
account.type = params[:data][:type]
-
-
5
output = AccountAdapter.new
-
-
5
output.on(:account_not_found) do |account|
-
render json: {
-
errors: [{
-
failed_login: 'Account not found, or not activated',
-
}],
-
}, status: :unprocessable_entity
-
end
-
-
5
output.on(:Please_enter_valid_student_id_or_account_not_activated) do |account|
-
1
render json: {
-
errors: [{
-
failed_login: 'Please enter valid student id, or account not activated',
-
}],
-
}, status: :unprocessable_entity
-
end
-
-
5
output.on(:Account_does_not_exits) do |account|
-
1
render json: {
-
errors: [{
-
failed_login: 'Account_does_not_exits',
-
-
}],
-
}, status: :unprocessable_entity
-
end
-
-
5
output.on(:Please_enter_valid_pin) do |account|
-
1
render json: {
-
errors: [{
-
failed_login: 'Please enter valid pin',
-
}],
-
}, status: :unprocessable_entity
-
end
-
-
# output.on(:failed_login) do |account|
-
# render json: {
-
# errors: [{
-
# failed_login: 'Login Failed',
-
# }],
-
# }, status: :unauthorized
-
# end
-
-
5
output.on(:successful_login) do |account, token, refresh_token|
-
2
render json: AccountBlock::AccountSerializer.new( account, meta: {
-
token: token, refresh_token: refresh_token}).as_json.merge({step: 4, message: "You have successfully login"})
-
-
end
-
-
5
output.login_account(account)
-
else
-
1
render json: {
-
errors: [{
-
account: 'Account not exist.',
-
}],
-
}, status: :unprocessable_entity
-
end
-
end
-
end
-
end
-
module BxBlockMultipageforms2
-
class ApplicationController < BuilderBase::ApplicationController
-
include BuilderJsonWebToken::JsonWebTokenValidation
-
-
# before_action :validate_json_web_token
-
-
rescue_from ActiveRecord::RecordNotFound, :with => :not_found
-
-
private
-
-
def not_found
-
render :json => {'errors' => ['Record not found']}, :status => :not_found
-
end
-
end
-
end
-
module BxBlockMultipageforms2
-
class UserProfilesController < ApplicationController
-
def index
-
profiles = UserProfile.all
-
if profiles.present?
-
render json: UserProfileSerializer.new(profiles).serializable_hash
-
else
-
render json: {data: []},
-
status: :ok
-
end
-
end
-
-
def show
-
profile = UserProfile.find_by(id: params[:id])
-
-
return render json: {errors: [
-
{profile: 'Not found'},
-
]}, status: :not_found if profile.blank?
-
json_data = UserProfileSerializer.new(profile).serializable_hash
-
render json: json_data
-
end
-
-
-
def create
-
profile = UserProfile.new(profile_params)
-
if profile.save
-
render json: UserProfileSerializer.new(profile).serializable_hash,
-
status: :ok
-
else
-
render json: {message: "Something went wrong"},
-
status: :unprocessable_entity
-
end
-
end
-
-
def update
-
profile = UserProfile.find_by(id: params[:id])
-
-
return render json: {errors: [
-
{UserProfile: 'Not found'},
-
]}, status: :not_found if profile.blank?
-
-
update_profile = profile.update(profile_params)
-
-
if update_profile == true
-
render json: UserProfileSerializer.new(profile).serializable_hash
-
else
-
render json: {errors: format_activerecord_errors(profile.errors)},
-
status: :unprocessable_entity
-
end
-
end
-
-
def destroy
-
profile = UserProfile.find_by(id: params[:id])
-
return if profile.nil?
-
if profile.destroy
-
render json: {message: "Profile deleted succesfully!"}, status: :ok
-
else
-
render json: {message: "Something went wrong"}.serializable_hash,
-
status: :unprocessable_entity
-
end
-
end
-
-
private
-
def format_activerecord_errors(errors)
-
result = []
-
errors.each do |attribute, error|
-
result << { attribute => error }
-
end
-
result
-
end
-
-
def profile_params
-
params.require(:data)[:attributes].permit(
-
:first_name, :last_name, :phone_number, :email, :gender,
-
:country, :industry, :message
-
)
-
end
-
-
end
-
end
-
module BxBlockNavmenu
-
class ApplicationController < BuilderBase::ApplicationController
-
include BuilderJsonWebToken::JsonWebTokenValidation
-
-
before_action :validate_json_web_token
-
-
rescue_from ActiveRecord::RecordNotFound, :with => :not_found
-
-
private
-
-
def not_found
-
render :json => {'errors' => ['Record not found']}, :status => :not_found
-
end
-
end
-
end
-
module BxBlockNavmenu
-
class NavigationMenuController < ApplicationController
-
def create
-
puts " - params = #{params}"
-
navigation_attributes = jsonapi_deserialize(params)
-
puts " - navigation_attributes = #{navigation_attributes}"
-
service = BxBlockNavmenu::Create.new(navigation_attributes)
-
result = service.execute
-
result.collect do |menu|
-
NavigationMenuSerializer.new(menu).serializable_hash
-
end
-
render json: result, status: :ok
-
end
-
-
def index
-
navigation_menus = NavigationMenu.all
-
result = navigation_menus.collect do |menu|
-
NavigationMenuSerializer.new(menu).serializable_hash
-
end
-
render json: result, status: :ok
-
end
-
end
-
end
-
module BxBlockOfflinebrowsing2
-
class ApplicationController < BuilderBase::ApplicationController
-
include BuilderJsonWebToken::JsonWebTokenValidation
-
-
before_action :validate_json_web_token
-
-
rescue_from ActiveRecord::RecordNotFound, :with => :not_found
-
-
private
-
-
def not_found
-
render :json => {'errors' => ['Record not found']}, :status => :not_found
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
module BxBlockOrderManagement
-
class AddressesController < BxBlockOrderManagement::ApplicationController
-
before_action :current_user
-
before_action :render_address_not_found, unless: :address_found?, only: [:show, :destroy, :update]
-
-
def index
-
addresses = user_delivery_addresses
-
if addresses.present?
-
render json: AddressesSerializer.new(addresses).serializable_hash,
-
status: :ok
-
else
-
render json: {message: "No addresses exist"}, status: 404
-
end
-
end
-
-
def create
-
delivery_address = DeliveryAddress.new(
-
address_params.merge({account_id: @current_user.id})
-
)
-
delivery_address.is_default = true if user_delivery_addresses.blank?
-
delivery_address.save!
-
if delivery_address.is_default
-
DeliveryAddress.rest_addresses(delivery_address.id).where(
-
account_id: @current_user.id
-
).update_all(is_default: false)
-
end
-
render json: AddressesSerializer.new(delivery_address, serialize_options).serializable_hash,
-
message: "Address added successfully ", status: :ok
-
end
-
-
def show
-
render json: AddressesSerializer.new(@delivery_address, serialize_options).serializable_hash,
-
status: :ok
-
end
-
-
def destroy
-
@delivery_address.destroy
-
-
if @delivery_address.destroyed?
-
render json: {message: "Address deleted successfully"}, status: :ok
-
else
-
render json: "Address ID does not exist", status: 404
-
end
-
end
-
-
def update
-
begin
-
ActiveRecord::Base.transaction do
-
@delivery_address.update!(address_params)
-
if @delivery_address.is_default
-
DeliveryAddress.rest_addresses(@delivery_address.id).where(
-
account_id: @current_user.id
-
).update_all(is_default: false)
-
end
-
end
-
rescue => e
-
render json: {error: e.message}
-
return
-
end
-
render json: AddressesSerializer.new(@delivery_address, serialize_options).serializable_hash,
-
message: "Address updated successfully ", status: :ok
-
end
-
-
private
-
-
def render_address_not_found
-
render json: {message: "Address ID does not exist"}, status: 404
-
end
-
-
def user_delivery_addresses
-
@user_delivery_addresses ||= DeliveryAddress.where(account_id: @current_user.id)
-
end
-
-
def address_params
-
params.permit(
-
:name, :flat_no, :address_type, :address, :address_line_2, :zip_code, :phone_number,
-
:latitude, :longitude, :is_default, :state, :country, :city, :landmark, :address_for
-
)
-
end
-
-
def fetch_address
-
@delivery_address ||= DeliveryAddress.find_by(account_id: @current_user.id, id: params[:id])
-
end
-
-
def address_found?
-
fetch_address && @delivery_address
-
end
-
-
def serialize_options
-
{params: {user: @current_user}}
-
end
-
end
-
end
-
# rubocop:enable Metrics/MethodLength, Metrics/AbcSize, Naming/VariableNumber, Naming/MemoizedInstanceVariableName
-
# frozen_string_literal: true
-
-
module BxBlockOrderManagement
-
class AdminController < BxBlockOrderManagement::ApplicationController
-
before_action :verify_admin_token
-
-
def delivery_address_create
-
da = BxBlockOrderManagement::DeliveryAddress.create(
-
delivery_address_params
-
)
-
render json: {delivery_address: da} if da.save
-
end
-
-
private
-
-
def delivery_address_params
-
params.require(:delivery_address).permit(
-
:account_id, :address, :address_line_2, :address_type, :address_for,
-
:name, :flat_no, :zip_code, :phone_number, :latitude, :longitude,
-
:residential, :city, :state_code, :country_code, :state, :country,
-
:is_default, :landmark
-
)
-
end
-
-
def verify_admin_token
-
render json: {error: "Invalid admin token"} unless request.headers[:admintoken] == ENV["ADMIN_API_TOKEN"]
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
1
module BxBlockOrderManagement
-
1
class ApplicationController < BuilderBase::ApplicationController
-
1
include BuilderJsonWebToken::JsonWebTokenValidation
-
1
before_action :validate_json_web_token
-
1
before_action :current_user
-
1
include PublicActivity::StoreController
-
-
1
rescue_from ActiveRecord::RecordNotFound, with: :not_found
-
-
1
def current_user
-
24
@current_user = AccountBlock::Account.find(@token.id)
-
end
-
-
1
private
-
-
1
def not_found
-
render json: {"errors" => ["Record not found"]}, status: :not_found
-
end
-
end
-
end
-
# rubocop:enable Naming/AccessorMethodName
-
# frozen_string_literal: true
-
-
1
module BxBlockOrderManagement
-
1
class OrdersController < BxBlockOrderManagement::ApplicationController
-
# before_action :check_order_item, only: %i[show destroy]
-
1
before_action :check_order,
-
only: %i[update_payment_source update_order_status update_custom_label edit_custom_label add_address_to_order
-
apply_coupon add_order_items remove_order_items]
-
1
before_action :address, only: [:add_address_to_order]
-
-
1
def index
-
@past_orders = BxBlockOrderManagement::Order.where(account_id: @current_user.id, status:"created").order(created_at: :desc).excluding(@current_user.orders.last)
-
@recent_orders = BxBlockOrderManagement::Order.where(account_id: @current_user.id, status: "created").last
-
orders = {}
-
if @past_orders.present? || @recent_orders.present?
-
orders[:recent_orders] = MyOrderSerializer.new(@recent_orders) if @recent_orders.present?
-
orders[:past_orders] = MyOrderSerializer.new(@past_orders) if @past_orders.present?
-
render json: orders
-
else
-
render json: { message: 'No order record found.' }, status: 200
-
end
-
end
-
-
1
def create
-
4
if params[:ebook_id].present? || params[:bundle_management_id].present?
-
3
@res = AddProduct.new(params, @current_user).call
-
3
update_cart_total(@res.data) if @res.success?
-
3
if @res.success? && !@res.data.nil?
-
3
order = Order.includes(order_items: [catalogue: %i[category sub_category brand]]
-
).find(@res.data.id)
-
3
render json: {
-
data:
-
{
-
# coupon_message: if @cart_response.nil? || @cart_response.success?
-
# nil
-
# else
-
# @cart_response.msg
-
# end,
-
order: OrderSerializer.new(
-
order,
-
{
-
params: {
-
user: @current_user,
-
host: request.protocol + request.host_with_port
-
}
-
}
-
)
-
}
-
}, status: "200"
-
else
-
render json: {errors: @res.msg}, status: @res.code
-
end
-
else
-
1
render json: {msg: "ebook must be define"}, status: 422
-
end
-
end
-
-
1
def show
-
2
@order = Order.find_by(account_id: @current_user.id, id: params[:order_id])
-
2
if @order.present?
-
render json: MyOrderSerializer.new(
-
@order,
-
{params: {order: true, host: request.protocol + request.host_with_port}}
-
).serializable_hash, status: :ok
-
else
-
2
render json: {message: "Order ID does not exist (or) Order Id does not belong to the current user"}, status: 404
-
end
-
end
-
-
# def update_order_status
-
# if @order.in_cart? || @order.cancelled?
-
# render json: {error: "Your order is in cart."},
-
# status: :unprocessable_entity
-
# else
-
# ActiveRecord::Base.transaction do
-
# @order.update!(status: params[:status])
-
# render json: OrderSerializer.new(@order, serializable_options), status: 200
-
# end
-
# end
-
# end
-
-
# def cancel_order
-
# order = Order.find_by({account_id: @current_user.id, id: params[:order_id]})
-
# render json: {errors: ["Record not found"]}, status: 404 and return unless order.present?
-
-
# order_status_id = OrderStatus.find_or_create_by(
-
# status: "cancelled", event_name: "cancel_order"
-
# ).id
-
# if order.in_cart?
-
# render json: {error: "Your order is in cart. so no need to cancel it"},
-
# status: :unprocessable_entity
-
# elsif order.status == "cancelled"
-
# render json: {message: "Order already cancelled"},
-
# status: :ok
-
# else
-
# begin
-
# ActiveRecord::Base.transaction do
-
# order.order_items.map do |a|
-
# a.update(
-
# order_status_id: order_status_id, cancelled_at: Time.current
-
# )
-
# end
-
# if order.full_order_cancelled?
-
# order.update(
-
# order_status_id: order_status_id,
-
# status: "cancelled",
-
# cancelled_at: Time.current
-
# )
-
# end
-
# end
-
# rescue => e
-
# render json: {error: e}
-
# end
-
# render json: {message: "Order cancelled successfully"},
-
# status: :ok
-
# end
-
# end
-
-
# def destroy
-
# if @order.account_id == @current_user.id
-
# @order.destroy
-
# if @order.destroyed?
-
# render json: {message: "Order deleted successfully"}, status: :ok
-
# else
-
# render json: "Order ID does not exist", status: 404
-
# end
-
# end
-
# end
-
-
# def add_address_to_order
-
# x = AddAddressToOrder.new(params, @current_user).call
-
# @order.update(delivery_address_id: params[:address_id])
-
# render json: {message: x.msg}, status: x.code
-
# end
-
-
# def apply_coupon
-
# if @order.status == "in_cart"
-
# @coupon = BxBlockCouponCg::CouponCode.find_by_code(params[:code])
-
# render(json: {message: "Invalid coupon"}, status: 400) && return if @coupon.nil?
-
# if @order.amount.present? && @order.amount < @coupon.min_cart_value
-
# return render json: {message: "Keep shopping to apply the coupon"}, status: 400
-
# end
-
-
# result = ApplyCoupon.new(@order, @coupon, params).call
-
# render json: {
-
# data: {
-
# coupon: OrderSerializer.new(@order), message: result.msg
-
# }
-
# }, status: 200
-
# else
-
# render json: {message: "Order not is in_cart"}
-
# end
-
# end
-
-
# def update_custom_label
-
# if params[:custom_label].present?
-
# if @order.update!(custom_label: params[:custom_label])
-
# render json: OrderSerializer.new(@order, serializable_options), status: 200
-
# end
-
# else
-
# render json: {msg: "custom_label must be define"}, status: 422
-
# end
-
# end
-
-
# def edit_custom_label
-
# if params[:custom_label].present?
-
# if @order.update!(custom_label: params[:custom_label])
-
# render json: OrderSerializer.new(@order, serializable_options), status: 200
-
# end
-
# else
-
# render json: {msg: "custom_label must be define"}, status: 422
-
# end
-
# end
-
-
1
def remove_order_items
-
4
if @order.status == "in_cart" || @order.status == "created"
-
3
if params[:order_items_ids].present?
-
2
err = []
-
2
msg = []
-
2
if OrderItem.find_by(id: params[:order_items_ids], order_management_order_id: params[:order_id])
-
1
msg << params[:order_items_ids]
-
else
-
1
err << params[:order_items_ids]
-
end
-
-
2
if !err.present?
-
1
OrderItem.destroy(msg)
-
1
render json: {message: "Order Items are deleted successfully"}, status: 200
-
else
-
1
render json: {message: "Order Items ids are does not exist with #{err}"}, status: 422
-
end
-
else
-
1
render json: {message: "Order Items ids are does not exist"}, status: 422
-
end
-
else
-
1
render json: {message: "Order not is in_cart or created"}, status: 422
-
end
-
end
-
-
1
def add_order_items
-
7
err = validate_order_items(order_item_params)
-
-
7
if order_status_valid? && err.empty?
-
2
create_order_items
-
else
-
5
render_error_message(err)
-
end
-
end
-
-
1
private
-
-
1
def validate_order_items(params)
-
7
errors = []
-
-
7
params.each do |key, value|
-
7
case key
-
when "ebook_id"
-
3
validate_ebook(value, errors)
-
when "bundle_management_id"
-
4
validate_bundle_management(value, errors)
-
else
-
render json: {message: "Items are not found"}, status: 404
-
end
-
end
-
-
7
errors.uniq
-
end
-
-
1
def validate_ebook(value, errors)
-
3
if value.present?
-
2
ebook = BxBlockBulkUploading::Ebook.find_by(id: value)
-
2
errors << "ebook does not exist" unless ebook.present?
-
else
-
1
errors << "ebook must be defined"
-
end
-
end
-
-
1
def validate_bundle_management(value, errors)
-
4
if value.present?
-
2
bundle_management = BxBlockBulkUploading::BundleManagement.find_by(id: value)
-
2
errors << "bundle does not exist" unless bundle_management.present?
-
else
-
2
errors << "bundle must be defined"
-
end
-
end
-
-
1
def order_status_valid?
-
12
@order.status == "in_cart" || @order.status == "created"
-
end
-
-
1
def create_order_items
-
2
@order.order_items.create!(order_item_params)
-
2
render json: OrderSerializer.new(@order, serializable_options), status: 200
-
end
-
-
1
def render_error_message(err)
-
5
if order_status_valid?
-
4
render json: { message: err }, status: 422
-
else
-
1
render json: { message: "Order is not in_cart or created" }, status: 422
-
end
-
end
-
-
# def address
-
# @address = DeliveryAddress.find_by(id: params[:address_id])
-
# render json: {message: "Delivery ID does not exist"}, status: 404 unless @address
-
# end
-
-
# def check_order_item
-
# @order = Order.find_by(account_id: @current_user.id, id: params[:id])
-
# unless @order
-
# render json: {message: "Order ID does not exist (or) Order Id does not belongs to current user"},
-
# status: 404
-
# end
-
# end
-
-
1
def check_order
-
13
@order = Order.find_by(account_id: @current_user.id, id: params[:order_id])
-
13
unless @order
-
2
render json: {message: "Order ID does not exist (or) Order Id does not belongs to current user"},
-
status: 404
-
end
-
end
-
-
1
def update_cart_total(order)
-
3
@cart_response = UpdateCartValue.new(order, @current_user).call
-
end
-
-
# def order_params
-
# params.permit(
-
# :order_number, :amount, :account_id,
-
# :delivery_address_id, :sub_total, :total, :status, :applied_discount, :cancellation_reason, :order_date,
-
# :is_gift, :placed_at, :confirmed_at, :in_transit_at, :delivered_at, :cancelled_at, :refunded_at,
-
# :source, :shipment_id, :delivery_charges, :tracking_url, :schedule_time, :payment_failed_at, :returned_at,
-
# :tax_charges, :deliver_by, :tracking_number, :is_error, :delivery_error_message, :payment_pending_at, :order_status_id,
-
# :is_group, :is_availability_checked, :shipping_charge, :shipping_discount, :shipping_net_amt, :shipping_total, :total_tax,
-
# :razorpay_order_id, :charged, :invoiced, :invoice_id,
-
# :ebook_id, :bundle_management_id, :order_id
-
# )
-
# end
-
-
1
def serializable_options
-
2
{params: {host: request.protocol + request.host_with_port}}
-
end
-
-
1
def order_item_params
-
# params.permit(order_items: %i[ebook_id bundle_management_id order_id]).require(:order_items)
-
9
params.require(:order_items).permit(:ebook_id, :bundle_management_id )
-
end
-
end
-
end
-
-
# rubocop:enable Metrics/MethodLength, Metrics/AbcSize, Metrics/ClassLength, Layout/LineLength, Metrics/CyclomaticComplexity, Metrics/PerceivedComplexity
-
module BxBlockPayments
-
class ApplicationController < BuilderBase::ApplicationController
-
include BuilderJsonWebToken::JsonWebTokenValidation
-
-
before_action :validate_json_web_token
-
-
rescue_from ActiveRecord::RecordNotFound, :with => :not_found
-
-
private
-
-
def current_user
-
@current_user ||= AccountBlock::Account.find(@token.id) if @token.present?
-
end
-
-
def not_found
-
render :json => {'errors' => ['Record not found']}, :status => :not_found
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
require 'razorpay'
-
-
module BxBlockPayments
-
class RazorpaysController < ApplicationController
-
before_action :get_transaction, only: [:show, :update]
-
before_action :check_expiry, only: [:update]
-
-
def show
-
render json: {transaction: @transaction }, status: :ok
-
end
-
-
def create
-
plan = BxBlockPlan::Plan.find(params[:plan_id])
-
if plan.present?
-
order = Razorpay::Order.create amount: params[:amount].to_i * 100, currency: 'INR', receipt: plan.name
-
transaction = current_user.transactions.create(order_id: order.id)
-
if transaction.save
-
render json: {transaction: transaction}, status: :created
-
else
-
render json: { error: transaction.errors}, status: :unprocessable_entity
-
end
-
end
-
end
-
-
def update
-
order = Razorpay::Order.fetch(params[:order_id])
-
if order.status == "created"
-
@transaction.update(status: params[:payment_response], razorpay_payment_id: params[:razorpay_payment_id], razorpay_order_id: params[:order_id])
-
render json: {transaction: @transaction , message: "Your transaction was successfully Done"}, class_name: "BxBlockPayments::Transaction"
-
else
-
@transaction.update(status: params[:payment_response], razorpay_payment_id: params[:razorpay_payment_id], razorpay_order_id: params[:order_id])
-
render json: {transaction: @transaction, message: "Your transaction was failed.
-
If your amount was deducted, then it will be refunded shortly." }, class_name: "BxBlockPayments::Transaction"
-
end
-
end
-
-
-
private
-
-
def check_expiry
-
if params[:duration] == "3 Months"
-
@expiry = Date.today + 90
-
elsif params[:duration] == "6 Months"
-
@expiry = Date.today + 180
-
elsif params[:duration] == "1 Year"
-
@expiry = Date.today + 365
-
else
-
render json: {error: "Invalid Date"}
-
end
-
end
-
-
def get_transaction
-
@transaction ||= BxBlockPayments::Transaction.find_by(order_id: params[:order_id])
-
if @transaction.blank?
-
render json: { error: "No transaction found !"}
-
end
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
module BxBlockPlan
-
class ApplicationController < BuilderBase::ApplicationController
-
include BuilderJsonWebToken::JsonWebTokenValidation
-
before_action :validate_json_web_token
-
end
-
end
-
# frozen_string_literal: true
-
-
module BxBlockPlan
-
class PlansController < ApplicationController
-
include BuilderJsonWebToken::JsonWebTokenValidation
-
before_action :validate_json_web_token, except: [:index]
-
-
def index
-
plans = BxBlockPlan::Plan.all
-
if plans.present?
-
render json: { plans: plans, message: 'Successfully Loaded' }
-
else
-
render json: { data: [] },
-
status: :ok
-
end
-
end
-
end
-
end
-
module BxBlockPosts
-
class ApplicationController < BuilderBase::ApplicationController
-
include BuilderJsonWebToken::JsonWebTokenValidation
-
include PublicActivity::StoreController
-
before_action :validate_json_web_token
-
-
rescue_from ActiveRecord::RecordNotFound, :with => :not_found
-
-
def current_user
-
@current_user ||= AccountBlock::Account.find(@token.id) if @token.present?
-
end
-
-
private
-
-
def not_found
-
render :json => {'errors' => ['Record not found']}, :status => :not_found
-
end
-
-
-
def check_account_activated
-
account = AccountBlock::Account.find_by(id: current_user.id)
-
unless account.activated
-
render json: { error: {
-
message: "Account has been not activated"}
-
}, status: :unprocessable_entity
-
end
-
end
-
end
-
end
-
module BxBlockPosts
-
class PostsController < ApplicationController
-
-
include BuilderJsonWebToken::JsonWebTokenValidation
-
-
before_action :validate_json_web_token
-
before_action :check_image_video_formate, only: [:create,:update]
-
before_action :check_account_activated
-
before_action :check_category, only: [:create,:update]
-
before_action :check_sub_category, only: [:create,:update]
-
-
def index
-
posts = BxBlockPosts::Post.all
-
if posts.present?
-
render json: PostSerializer.new(posts, params: {current_user: current_user}).serializable_hash
-
else
-
render json: {data: []},
-
status: :ok
-
end
-
end
-
-
def create
-
service = BxBlockPosts::Create.new(current_user, post_params)
-
new_post = service.execute
-
if new_post.persisted?
-
upload_post_images(new_post,params[:images])if params[:images].present?
-
media(new_post,params[:media]) if params[:media].present?
-
render json: PostSerializer.new(new_post).serializable_hash,
-
status: :ok
-
else
-
render json: ErrorSerializer.new(new_post).serializable_hash,
-
status: :unprocessable_entity
-
end
-
end
-
-
def show
-
post = BxBlockPosts::Post.find_by(id: params[:id])
-
-
return render json: {errors: [
-
{Post: 'Not found'},
-
]}, status: :not_found if post.blank?
-
json_data = PostSerializer.new(post, params: {current_user: current_user}).serializable_hash
-
render json: json_data
-
end
-
-
def update
-
post = BxBlockPosts::Post.find_by(id: params[:id], account_id: current_user.id)
-
-
return render json: {errors: [
-
{Post: 'Not found'},
-
]}, status: :not_found if post.blank?
-
post = BxBlockPosts::Update.new(post, post_params).execute
-
-
if post.persisted?
-
upload_post_images(post,params[:images])if params[:images].present?
-
media(post,params[:media]) if params[:media].present?
-
render json: PostSerializer.new(post, params: {current_user: current_user}).serializable_hash
-
else
-
render json: {errors: format_activerecord_errors(post.errors)},
-
status: :unprocessable_entity
-
end
-
end
-
-
def search
-
@posts = Post.where('description ILIKE :search', search: "%#{search_params[:query]}%")
-
render json: PostSerializer.new(@posts, params: {current_user: current_user}).serializable_hash, status: :ok
-
end
-
-
def destroy
-
post = BxBlockPosts::Post.find_by(id: params[:id], account_id: current_user.id)
-
render(json: { errors: 'post not found' }, status: :not_found) and return if post.nil?
-
if post.destroy
-
render json: {message: "Post deleted succesfully!"}, status: :ok
-
else
-
render json: ErrorSerializer.new(post).serializable_hash,
-
status: :unprocessable_entity
-
end
-
end
-
-
private
-
-
def post_params
-
params.permit(
-
:name, :description, :body, :category_id,:sub_category_id, :location,
-
tag_list: [],
-
images: [],
-
location_attributes: [:id, :address, :_destroy]
-
)
-
end
-
-
def search_params
-
params.permit(:query)
-
end
-
-
def format_activerecord_errors(errors)
-
result = []
-
errors.each do |attribute, error|
-
result << { attribute => error }
-
end
-
result
-
end
-
-
def check_image_video_formate
-
return if params[:images].blank?
-
image_formats = %w(image/jpeg image/jpg image/png)
-
video_formats = %w(video/mp4 video/mov video/wmv video/flv video/avi video/mkv video/webm)
-
params[:images].each do |image_data|
-
content_type = image_data[:content_type]
-
if image_formats.exclude?(image_data[:content_type]) && content_type == 'image'
-
render json: {errors: ["The image is unsupported type, supported formates are #{image_formats}"]},
-
status: :unprocessable_entity
-
elsif video_formats.exclude?(image_data[:content_type]) && content_type == 'video'
-
render json: {errors: ["The video is unsupported type, supported formates are #{video_formats}"]},
-
status: :unprocessable_entity
-
end
-
end
-
end
-
-
def upload_post_images(post,images_params)
-
images_to_attach = []
-
-
images_params.each do |image_data|
-
if image_data[:data]
-
decoded_data = Base64.decode64(image_data[:data].split(',')[0])
-
images_to_attach.push(
-
io: StringIO.new(decoded_data),
-
content_type: image_data[:content_type],
-
filename: image_data[:filename]
-
)
-
end
-
end
-
post.images.attach(images_to_attach) if images_to_attach.size.positive?
-
end
-
-
def media(post,images_params)
-
images_to_attach = []
-
-
images_params.each do |image_data|
-
if image_data[:data]
-
decoded_data = Base64.decode64(image_data[:data].split(',')[0])
-
images_to_attach.push(
-
io: StringIO.new(decoded_data),
-
content_type: image_data[:content_type],
-
filename: image_data[:filename]
-
)
-
end
-
end
-
post.media.attach(images_to_attach) if images_to_attach.size.positive?
-
end
-
-
def check_category
-
@category = BxBlockCategories::Category.find_by(id: params[:category_id])
-
unless @category
-
render json: {message: "Category ID does not exist"},
-
status: 404
-
end
-
end
-
-
def check_sub_category
-
@sub_category = BxBlockCategories::SubCategory.find_by(id: params[:sub_category_id])
-
unless @sub_category
-
render json: {message: "Sub_category ID does not exist"},
-
status: 404
-
end
-
end
-
end
-
end
-
1
module BxBlockProfile
-
1
class ApplicationController < BuilderBase::ApplicationController
-
1
include BuilderJsonWebToken::JsonWebTokenValidation
-
1
before_action :validate_json_web_token
-
# serialization_scope :view_context
-
-
1
private
-
-
1
def format_activerecord_errors(errors)
-
result = []
-
errors.each do |attribute, error|
-
result << { attribute => error }
-
end
-
result
-
end
-
end
-
end
-
module BxBlockProfile
-
class AwardsController < ApplicationController
-
-
def create
-
@profile = current_user.profiles.find_by(profile_role:"jobseeker")
-
-
if @profile.present?
-
@awards = BxBlockProfile::Award.new(award_params.merge({profile_id: @profile.id}))
-
-
if @awards.save
-
render json: BxBlockProfile::AwardSerializer.new(@awards
-
).serializable_hash, status: :created
-
else
-
render json: {
-
errors: format_activerecord_errors(@awards.errors)
-
}, status: :unprocessable_entity
-
end
-
else
-
return render json: {errors: [
-
{profile: 'No jobseeker profile exist for this account'},
-
]}, status: :unprocessable_entity
-
end
-
end
-
-
def index
-
@awards = BxBlockProfile::Award.all
-
if @awards.present?
-
render json: BxBlockProfile::AwardSerializer.new(@awards, meta: {
-
message: "Awards List"
-
}).serializable_hash, status: :ok
-
else
-
render json:{meta: {message: "Record not found."}}
-
end
-
end
-
-
def show
-
award = BxBlockProfile::Award.find_by({id: params[:id]})
-
-
if award.present?
-
render json: BxBlockProfile::AwardSerializer.new(award, meta: {
-
message: "here is the profile with the given id"
-
}).serializable_hash, status: :ok
-
-
else
-
render json:{meta: {message: "Record not found."}}
-
end
-
end
-
-
def destroy
-
award = BxBlockProfile::Award.find_by({id: params[:id]})
-
if award&.destroy
-
render json:{ meta: { message: "Award Removed"}}
-
else
-
render json:{meta: {message: "Record not found."}}
-
end
-
end
-
-
private
-
-
def current_user
-
@account = AccountBlock::Account.find_by(id: @token.id)
-
end
-
-
def award_params
-
params.require(:award).permit \
-
:title,
-
:associated_with,
-
:issuer,
-
:issue_date,
-
:description,
-
:make_public
-
end
-
end
-
end
-
module BxBlockProfile
-
class CareerExperiencesController < ApplicationController
-
def index
-
@career_experiences = CareerExperience.all
-
render json: CareerExperienceSerializer.new(@career_experiences, meta: {
-
message: "Successfully Loaded"
-
}).serializable_hash, status: :ok
-
end
-
-
def create
-
@profile = current_user.profiles.find_by(profile_role:"jobseeker")
-
-
if @profile.present?
-
@career_experience = BxBlockProfile::CareerExperience.new(
-
career_experience_params.merge({ profile_id: @profile.id} ))
-
if @career_experience.save
-
create_industry && create_employment_type && create_system_experience
-
render json: BxBlockProfile::CareerExperienceSerializer.new(@career_experience
-
).serializable_hash, status: :created
-
else
-
render json: {
-
errors: format_activerecord_errors(@career_experience.errors)
-
}, status: :unprocessable_entity
-
end
-
else
-
return render json: {errors: [
-
{profile: 'No jobseeker profile exist for this account'},
-
]}, status: :unprocessable_entity
-
end
-
end
-
-
def show
-
ce = BxBlockProfile::CareerExperience.find_by({id: params[:id]})
-
-
if ce.present?
-
render json: CareerExperienceSerializer.new(ce, meta: {
-
message: "Career Experience"
-
}).serializable_hash, status: :ok
-
-
else
-
render json:{meta: {message: "Record not found."}}
-
end
-
end
-
-
def update
-
career_experience = BxBlockProfile::CareerExperience.find_by(id: params[:id])
-
if career_experience.present?
-
career_experience.update(career_experience_params)
-
render json: CareerExperienceSerializer.new(career_experience, meta: {
-
message: "Career Experience updated successfully"
-
}).serializable_hash, status: :ok
-
else
-
render json: {
-
errors: format_activerecord_errors(career_experience.errors)
-
}, status: :unprocessable_entity
-
end
-
end
-
-
def destroy
-
career_experience = BxBlockProfile::CareerExperience.find_by(id: params[:id])
-
if career_experience&.destroy
-
render json:{ meta: { message: "Career Experience Removed"}}
-
else
-
render json:{meta: {message: "Record not found."}}
-
end
-
end
-
-
private
-
-
def current_user
-
@account = AccountBlock::Account.find_by(id: @token.id)
-
end
-
-
def career_experience_params
-
params.require(:career_experience).permit \
-
:id,
-
:job_title,
-
:start_date,
-
:end_date,
-
:company_name,
-
:description,
-
:make_key_achievements_public,
-
:current_salary,
-
:currently_working_here,
-
:notice_period,
-
:notice_period_end_date,
-
add_key_achievements: []
-
end
-
-
def create_industry
-
industry = Industry.where(industry_name: params[:industry_name]).first
-
if industry.present?
-
CareerExperienceIndustry.create(career_experience_id: @career_experience.id, industry_id: industry.id)
-
else
-
industry = Industry.create(industry_name: params[:industry_name])
-
CareerExperienceIndustry.create(career_experience_id: @career_experience.id, industry_id: industry.id)
-
end
-
end
-
-
def create_employment_type
-
employment_type = EmploymentType.where(employment_type_name: params[:employment_type_name]).first
-
if employment_type.present?
-
CareerExperienceEmploymentType.create(career_experience_id: @career_experience.id,
-
employment_type_id: employment_type.id)
-
else
-
employment_type = EmploymentType.create(employment_type_name: params[:employment_type_name])
-
CareerExperienceEmploymentType.create(career_experience_id: @career_experience.id,
-
employment_type_id: employment_type.id)
-
end
-
end
-
-
def create_system_experience
-
system_experience = SystemExperience.where(system_experience: params[:system_experience]).first
-
if system_experience.present?
-
CareerExperienceSystemExperience.create(career_experience_id: @career_experience.id,
-
system_experience_id: system_experience.id)
-
else
-
system_experience = SystemExperience.create(system_experience: params[:system_experience])
-
CareerExperienceSystemExperience.create(career_experience_id: @career_experience.id,
-
system_experience_id: system_experience.id)
-
end
-
end
-
-
end
-
end
-
module BxBlockProfile
-
class ChangePhoneValidationsController < ApplicationController
-
def create
-
validator = ChangePhoneValidator
-
.new(@token.id, create_params[:new_phone_number])
-
-
if validator.valid?
-
render json: {
-
messages: [{
-
profile: 'Phone number change is valid',
-
}],
-
}, status: :created
-
else
-
errors = validator.errors.full_messages
-
render :json => {:errors => [{:profile => errors.first}]},
-
:status => :unprocessable_entity
-
end
-
end
-
-
private
-
-
def create_params
-
params.require(:data).permit :new_phone_number
-
end
-
end
-
end
-
module BxBlockProfile
-
class CoursesController < ApplicationController
-
-
def create
-
@profile = current_user.profiles.find_by(profile_role:"jobseeker")
-
-
if @profile.present?
-
@courses = BxBlockProfile::Course.new(courses_params.merge({profile_id: @profile.id}))
-
if @courses.save
-
render json: BxBlockProfile::CourseSerializer.new(@courses
-
).serializable_hash, status: :created
-
else
-
render json: {
-
errors: format_activerecord_errors(@courses.errors)
-
}, status: :unprocessable_entity
-
end
-
else
-
return render json: {errors: [
-
{profile: 'No jobseeker profile exist for this account'},
-
]}, status: :unprocessable_entity
-
end
-
end
-
-
def index
-
@courses = BxBlockProfile::Course.all
-
if @courses.present?
-
render json: BxBlockProfile::CourseSerializer.new(@courses, meta: {
-
message: "Courses List"
-
}).serializable_hash, status: :ok
-
else
-
render json:{meta: {message: "Record not found."}}
-
end
-
end
-
-
def show
-
course = BxBlockProfile::Course.find_by({id: params[:id]})
-
if course.present?
-
render json: BxBlockProfile::CourseSerializer.new(course, meta: {
-
message: "here is the course with the given id"
-
}).serializable_hash, status: :ok
-
else
-
render json:{meta: {message: "Record not found."}}
-
end
-
end
-
-
def destroy
-
course = BxBlockProfile::Course.find_by({id: params[:id]})
-
if course&.destroy
-
render json:{ meta: { message: "Course Removed"}}
-
else
-
render json:{meta: {message: "Record not found."}}
-
end
-
end
-
private
-
-
def current_user
-
@account = AccountBlock::Account.find_by(id: @token.id)
-
end
-
-
def courses_params
-
params.require(:courses).permit \
-
:course_name,
-
:duration,
-
:year
-
end
-
end
-
end
-
module BxBlockProfile
-
class CurrentStatusController < ApplicationController
-
-
def create
-
@profile = current_user.profiles.find_by(profile_role:"jobseeker")
-
if @profile.present?
-
@current_status = @profile.create_current_status(current_status_params)
-
-
if @current_status.save
-
create_industry && create_employment_type && create_current_annual_salary
-
render json: BxBlockProfile::CurrentStatusSerializer.new(@current_status
-
).serializable_hash, status: :created
-
else
-
render json: {
-
errors: format_activerecord_errors(@current_status.errors)
-
}, status: :unprocessable_entity
-
end
-
else
-
return render json: {errors: [
-
{profile: 'No jobseeker profile exist for this account'},
-
]}, status: :unprocessable_entity
-
end
-
end
-
-
private
-
-
def current_user
-
@account = AccountBlock::Account.find_by(id: @token.id)
-
end
-
-
def current_status_params
-
params.require(:current_status).permit \
-
:most_recent_job_title,
-
:company_name,
-
:notice_period,
-
:end_date
-
end
-
-
def create_industry
-
industry = Industry.where(industry_name: params[:industry_name]).first
-
if industry.present?
-
CurrentStatusIndustry.create(current_status_id: @current_status.id, industry_id: industry.id)
-
else
-
industry = Industry.create(industry_name: params[:industry_name])
-
CurrentStatusIndustry.create(current_status_id: @current_status.id, industry_id: industry.id)
-
end
-
end
-
-
def create_employment_type
-
employment_type = EmploymentType.where(employment_type_name: params[:employment_type_name]).first
-
if employment_type.present?
-
CurrentStatusEmploymentType.create(current_status_id: @current_status.id,
-
employment_type_id: employment_type.id)
-
else
-
employment_type = EmploymentType.create(employment_type_name: params[:employment_type_name])
-
CurrentStatusEmploymentType.create(current_status_id: @current_status.id,
-
employment_type_id: employment_type.id)
-
end
-
end
-
-
def create_current_annual_salary
-
current_annual_salary = CurrentAnnualSalary.where(current_annual_salary: params[:current_annual_salary]).first
-
if current_annual_salary.present?
-
CurrentAnnualSalaryCurrentStatus.create(current_status_id: @current_status.id,
-
current_annual_salary_id: current_annual_salary.id)
-
else
-
current_annual_salary = CurrentAnnualSalary.create(current_annual_salary: params[:current_annual_salary])
-
CurrentAnnualSalaryCurrentStatus.create(current_status_id: @current_status.id,
-
current_annual_salary_id: current_annual_salary.id)
-
end
-
end
-
-
end
-
end
-
module BxBlockProfile
-
class EducationalQualificationsController < ApplicationController
-
-
def index
-
@educational_qualifications = EducationalQualification.all
-
render json: EducationalQualificationSerializer.new(@educational_qualifications, meta: {
-
message: "Successfully Loaded"
-
}).serializable_hash, status: :ok
-
#render json: {educational_qualifications: @educational_qualifications, full_messages: "Successfully Loaded"}
-
end
-
-
def create
-
@profile = current_user.profiles.find_by(profile_role:"jobseeker")
-
-
if @profile.present?
-
@educational_qualification = BxBlockProfile::EducationalQualification.new(
-
educational_qualification_params.merge({ profile_id: @profile.id} ))
-
-
if @educational_qualification.save
-
create_field_study && create_degree
-
render json: BxBlockProfile::EducationalQualificationSerializer.new(@educational_qualification
-
).serializable_hash, status: :created
-
else
-
render json: {
-
errors: format_activerecord_errors(@educational_qualification.errors)
-
}, status: :unprocessable_entity
-
end
-
else
-
return render json: {errors: [
-
{profile: 'No jobseeker profile exist for this account'},
-
]}, status: :unprocessable_entity
-
end
-
end
-
-
def show
-
educational_qualification = BxBlockProfile::EducationalQualification.find_by(id: params[:id])
-
render json: EducationalQualificationSerializer.new(educational_qualification, meta: {
-
message: ""
-
}).serializable_hash, status: :ok
-
end
-
-
def update
-
educational_qualification = BxBlockProfile::EducationalQualification.find_by(id: params[:id])
-
if educational_qualification.present?
-
educational_qualification.update(educational_qualification_params)
-
render json: EducationalQualificationSerializer.new(educational_qualification, meta: {
-
message: "Educational Qualification updated successfully"
-
}).serializable_hash, status: :ok
-
else
-
render json: {
-
errors: format_activerecord_errors(educational_qualification.errors)
-
}, status: :unprocessable_entity
-
end
-
end
-
-
def destroy
-
educational_qualification = BxBlockProfile::EducationalQualification.find_by(id: params[:id])
-
if educational_qualification&.destroy
-
render json:{ meta: { message: "Educational Qualification Removed"}}
-
else
-
render json:{meta: {message: "Record not found."}}
-
end
-
end
-
-
-
private
-
-
def current_user
-
@account = AccountBlock::Account.find_by(id: @token.id)
-
end
-
-
def educational_qualification_params
-
params.require(:educational_qualification).permit \
-
:id,
-
:school_name,
-
:start_date,
-
:end_date,
-
:grades,
-
:description,
-
:make_grades_public
-
end
-
-
def create_field_study
-
field_study = FieldStudy.where(field_of_study: params[:field_of_study]).first
-
if field_study.present?
-
EducationalQualificationFieldStudy.create(educational_qualification_id: @educational_qualification.id,
-
field_study_id: field_study.id)
-
else
-
field_study = FieldStudy.create(field_of_study: params[:field_of_study])
-
EducationalQualificationFieldStudy.create(educational_qualification_id: @educational_qualification.id,
-
field_study_id: field_study.id)
-
end
-
end
-
-
def create_degree
-
degree = Degree.where(degree_name: params[:degree_name]).first
-
if degree.present?
-
DegreeEducationalQualification.create(educational_qualification_id: @educational_qualification.id,
-
degree_id: degree.id)
-
else
-
degree = Degree.create(degree_name: params[:degree_name])
-
DegreeEducationalQualification.create(educational_qualification_id: @educational_qualification.id,
-
degree_id: degree.id)
-
end
-
end
-
-
end
-
end
-
module BxBlockProfile
-
class EmploymentTypesController < ApplicationController
-
skip_before_action :validate_json_web_token
-
def create
-
@emp_type = BxBlockProfile::EmploymentType.create(emp_type_params)
-
if @emp_type.save
-
render json: { data: @emp_type, message: 'New Employment Type Added' }, status: :created
-
else
-
render json: {
-
errors: format_activerecord_errors(@emp_type.errors)
-
}, status: :unprocessable_entity
-
end
-
end
-
-
def index
-
@emp_types = BxBlockProfile::EmploymentType.all
-
render json: { data: @emp_types }, status: :ok
-
end
-
-
def show
-
@emp_type = BxBlockProfile::EmploymentType.find(params[:id])
-
render json: { data: @emp_type }, status: :ok
-
end
-
-
private
-
-
def emp_type_params
-
params.require(:employment_type).permit \
-
:employment_type_name
-
end
-
end
-
end
-
module BxBlockProfile
-
class HobbiesController < ApplicationController
-
-
def create
-
@profile = current_user.profiles.find_by(profile_role:"jobseeker")
-
-
if @profile.present?
-
@hobbies = BxBlockProfile::Hobby.new(hobbies_params.merge({profile_id: @profile.id}))
-
if @hobbies.save
-
render json: BxBlockProfile::HobbySerializer.new(@hobbies
-
).serializable_hash, status: :created
-
else
-
render json: {
-
errors: format_activerecord_errors(@hobbies.errors)
-
}, status: :unprocessable_entity
-
end
-
else
-
return render json: {errors: [
-
{profile: 'No jobseeker profile exist for this account'},
-
]}, status: :unprocessable_entity
-
end
-
end
-
-
def index
-
@hobbies = BxBlockProfile::Hobby.all
-
if @hobbies.present?
-
render json: BxBlockProfile::HobbySerializer.new(@hobbies, meta: {
-
message: "Hobbies List"
-
}).serializable_hash, status: :ok
-
else
-
render json:{meta: {message: "Record not found."}}
-
end
-
end
-
-
def show
-
hobby = BxBlockProfile::Hobby.find_by({id: params[:id]})
-
if hobby.present?
-
render json: BxBlockProfile::HobbySerializer.new(hobby, meta: {
-
message: "here is the hobby with the given id"
-
}).serializable_hash, status: :ok
-
else
-
render json:{meta: {message: "Record not found."}}
-
end
-
end
-
-
def destroy
-
hobby = BxBlockProfile::Hobby.find_by({id: params[:id]})
-
if hobby&.destroy
-
render json:{ meta: { message: "Hobyy Removed"}}
-
else
-
render json:{meta: {message: "Record not found."}}
-
end
-
end
-
private
-
-
def current_user
-
@account = AccountBlock::Account.find_by(id: @token.id)
-
end
-
-
def hobbies_params
-
params.require(:hobbies).permit \
-
:title,
-
:category,
-
:description,
-
:make_public
-
end
-
end
-
end
-
module BxBlockProfile
-
class LanguagesController < ApplicationController
-
-
before_action :validate_json_web_token
-
-
PROFICIENCY = [:mediam, :advance]
-
-
def proficiency
-
render json: {proficiences: BxBlockProfile::LanguagesController::PROFICIENCY }
-
end
-
-
def index
-
@languages = Language.all
-
render json: {languages: @languages, full_messages: "Successfully Loaded"}
-
end
-
-
def create
-
@profile = current_user.profiles.find_by(profile_role:"jobseeker")
-
if @profile.present?
-
-
@language = BxBlockProfile::Language.new(language_params.merge({ profile_id: @profile.id} ))
-
if @language.save
-
render json: BxBlockProfile::LanguageSerializer.new(@language
-
).serializable_hash, status: :created
-
else
-
render json: {
-
errors: format_activerecord_errors(@language.errors)
-
}, status: :unprocessable_entity
-
end
-
else
-
return render json: {errors: [
-
{profile: 'No jobseeker profile exist for this account'},
-
]}, status: :unprocessable_entity
-
end
-
end
-
-
def show
-
language = BxBlockProfile::Language.find_by(id: params[:id])
-
-
if language.present?
-
render json: BxBlockProfile::LanguageSerializer.new(language, meta: {
-
message: ""
-
}).serializable_hash, status: :ok
-
else
-
render json:{meta: {message: "Record not found."}}
-
end
-
end
-
-
def update
-
language = BxBlockProfile::Language.find_by(id: params[:id])
-
if language.present?
-
language.update(language_params)
-
render json: LanguageSerializer.new(language, meta: {
-
message: "Language updated successfully"
-
}).serializable_hash, status: :ok
-
else
-
render json: {
-
errors: format_activerecord_errors(language.errors)
-
}, status: :unprocessable_entity
-
end
-
end
-
-
def destroy
-
language = BxBlockProfile::Language.find_by(id: params[:id])
-
if language&.destroy
-
render json:{ meta: { message: "Language Removed"}}
-
else
-
render json:{meta: {message: "Record not found."}}
-
end
-
end
-
-
-
private
-
-
def encode(id)
-
BuilderJsonWebToken.encode id
-
end
-
-
def current_user
-
@account = AccountBlock::Account.find_by(id: @token.id)
-
end
-
-
def language_params
-
params.require(:language).permit \
-
:id,
-
:language,
-
:proficiency
-
end
-
end
-
end
-
1
module BxBlockProfile
-
1
class PasswordsController < ApplicationController
-
1
before_action :validate_json_web_token
-
-
1
def reset_password
-
3
if params[:data][:pin] != params[:data][:confirm_pin]
-
1
return render json: {message: "confirm pin is wrong"}
-
end
-
2
@account = AccountBlock::Account.find(@token.id)
-
1
render json: {errors: "Record not found"} unless @account.present?
-
1
if @account.update(pin: params[:data][:pin], is_reset: false, one_time_pin: "")
-
1
render json: AccountBlock::AccountSerializer.new(@account).serializable_hash, status: :ok
-
end
-
end
-
-
# def update
-
# status, result = ChangePasswordCommand.execute \
-
# @token.id,
-
# update_params[:current_password],
-
# update_params[:new_password]
-
-
# if status == :created
-
# serializer = AccountBlock::AccountSerializer.new(result)
-
# render :json => serializer.serializable_hash,
-
# :status => :created
-
# else
-
# render :json => {:errors => [{:profile => result.first}]},
-
# :status => status
-
# end
-
# end
-
-
1
private
-
-
# def update_params
-
# params.require(:data)
-
# .permit \
-
# :current_password,
-
# :new_password
-
# end
-
end
-
end
-
1
module BxBlockProfile
-
1
class ProfilesController < ApplicationController
-
1
before_action :validate_json_web_token, :current_user, only: [:show, :update]
-
-
1
def show
-
5
profile = current_user.profile
-
5
if profile&.present?
-
4
render json: ProfileSerializer.new(profile, serialization_options).serializable_hash,status: :ok
-
else
-
1
render json: {
-
message: "Profile not found"
-
}, status: :unprocessable_entity
-
end
-
end
-
-
1
def show_about_us
-
2
term = BxBlockTermsAndConditions::TermsAndCondition.last
-
2
about_us = BxBlockContentManagement::AboutUs.last
-
2
if term.present? && about_us.present?
-
1
render json: {data: {content:[{type: "Term", term: term}, {type: "About Us", about_us: about_us}]}}, status: :ok
-
else
-
1
render json: {message: "Data not found"}, status: :not_found
-
end
-
end
-
-
1
def show_faq
-
2
faq = BxBlockContentManagement::FaqQuestion.all
-
2
if faq.present?
-
1
render json: {data: {faq: faq}}, status: :ok
-
else
-
1
render json: {message: "Data not found"}, status: :not_found
-
end
-
end
-
-
1
def update
-
5
profile = current_user.profile
-
5
if profile&.present?
-
4
if profile&.update(profile_params)
-
4
current_user.update(profile_params.merge(first_name: profile_params[:user_name]))
-
4
render json: ProfileSerializer.new(profile, serialization_options).serializable_hash, status: :ok
-
else
-
render json: { message: "Profile update failed" }, status: :unprocessable_entity
-
end
-
else
-
1
render json: { message: "Invalid parameters for the user role" }, status: :unprocessable_entity
-
end
-
end
-
-
1
private
-
-
1
def current_user
-
24
@account = AccountBlock::Account.find_by(id: @token.id)
-
end
-
-
1
def serialization_options
-
8
{ params: { host: request.protocol + request.host_with_port } }
-
end
-
-
# Added required params need to be updated
-
1
def profile_params
-
12
params.require(:profile).permit(:photo,:user_name, :guardian_email,:school_id, :student_unique_id, :guardian_name, :guardian_contact_no, :email, :teacher_unique_id, :school_id, :full_phone_number, :employee_unique_id,:publication_house_name, :first_name, :last_name, :department )
-
end
-
end
-
end
-
module BxBlockProfile
-
class ProjectsController < ApplicationController
-
-
def index
-
@projects = Project.all
-
render json: ProjectSerializer.new(@projects, meta: {
-
message: "Successfully Loaded"
-
}).serializable_hash, status: :ok
-
end
-
-
def create
-
@profile = current_user.profiles.find_by(profile_role:"jobseeker")
-
if @profile.present?
-
@project = BxBlockProfile::Project.new(project_params.merge({ profile_id: @profile.id} ))
-
if @project.save
-
create_associated_with
-
render json: BxBlockProfile::ProjectSerializer.new(@project
-
).serializable_hash, status: :created
-
else
-
render json: {
-
errors: format_activerecord_errors(@project.errors)
-
}, status: :unprocessable_entity
-
end
-
else
-
render json: {
-
errors: format_activerecord_errors(@profile.errors)
-
}, status: :unprocessable_entity
-
end
-
end
-
-
def show
-
project = BxBlockProfile::Project.find_by(id: params[:id])
-
if project.present?
-
render json: BxBlockProfile::ProjectSerializer.new(project, meta: {
-
message: ""
-
}).serializable_hash, status: :ok
-
else
-
render json:{meta: {message: "Record not found."}}
-
end
-
end
-
-
def update
-
project = BxBlockProfile::Project.find_by(id: params[:id])
-
if project.present?
-
project.update(project_params)
-
render json: ProjectSerializer.new(project, meta: {
-
message: "Project updated successfully"
-
}).serializable_hash, status: :ok
-
else
-
render json: {
-
errors: format_activerecord_errors(project.errors)
-
}, status: :unprocessable_entity
-
end
-
end
-
-
def destroy
-
project = BxBlockProfile::Project.find_by(id: params[:id])
-
if project&.destroy
-
render json:{ meta: { message: "Project Removed"}}
-
else
-
render json:{meta: {message: "Record not found."}}
-
end
-
end
-
-
private
-
-
def current_user
-
@account = AccountBlock::Account.find_by(id: @token.id)
-
end
-
-
def project_params
-
params.require(:project).permit \
-
:id,
-
:project_name,
-
:start_date,
-
:end_date,
-
:add_members,
-
:url,
-
:description,
-
:make_projects_public
-
end
-
-
def create_associated_with
-
associated = Associated.where(associated_with_name: params[:associated_with_name]).first
-
if associated.present?
-
AssociatedProject.create(project_id: @project.id, associated_id: associated.id)
-
else
-
associated = Associated.create(associated_with_name: params[:associated_with_name])
-
AssociatedProject.create(project_id: @project.id, associated_id: associated.id)
-
end
-
end
-
-
end
-
end
-
module BxBlockProfile
-
class PublicationPatentsController < ApplicationController
-
-
def create
-
@profile = current_user.profiles.find_by(profile_role:"jobseeker")
-
if @profile.present?
-
@publication_patent = @profile.create_publication_patent(publication_patent_params)
-
if @publication_patent.save
-
render json: BxBlockProfile::PublicationPatentSerializer.new(@publication_patent
-
).serializable_hash, status: :created
-
else
-
return render json: {errors: [
-
{profile: 'No jobseeker profile exist for this account'},
-
]}, status: :unprocessable_entity
-
end
-
end
-
end
-
-
def index
-
@pp = BxBlockProfile::PublicationPatent.all
-
if @pp.present?
-
render json: BxBlockProfile::PublicationPatentSerializer.new(@pp, meta: {
-
message: "List Of Publication"
-
}).serializable_hash, status: :ok
-
else
-
render json:{meta: {message: "Record not found."}}
-
end
-
end
-
-
def show
-
pp = BxBlockProfile::PublicationPatent.find(params[:id])
-
if pp.present?
-
render json: BxBlockProfile::PublicationPatentSerializer.new(pp, meta: {
-
message: "Here are the publication details"
-
}).serializable_hash, status: :ok
-
else
-
render json:{meta: {message: "Record not found."}}
-
end
-
end
-
-
def destroy
-
pp = BxBlockProfile::PublicationPatent.find_by(id: params[:id])
-
if pp&.destroy
-
render json:{ meta: { message: "Publication Removed"}}
-
else
-
render json:{meta: {message: "Record not found."}}
-
end
-
end
-
-
private
-
-
def current_user
-
@account = AccountBlock::Account.find_by(id: @token.id)
-
end
-
-
def publication_patent_params
-
params.require(:publication_patent).permit \
-
:title,
-
:publication,
-
:authors,
-
:url,
-
:description,
-
:make_public
-
end
-
end
-
end
-
module BxBlockProfile
-
class TestScoreAndCoursesController < ApplicationController
-
-
def create
-
@profile = current_user.profiles.find_by(profile_role:"jobseeker")
-
-
if @profile.present?
-
@test_score = BxBlockProfile::TestScoreAndCourse.new(test_score_params.merge({profile_id: @profile.id}))
-
if @test_score.save
-
render json: BxBlockProfile::TestScoreAndCourseSerializer.new(@test_score
-
).serializable_hash, status: :created
-
else
-
render json: {
-
errors: format_activerecord_errors(@test_score.errors)
-
}, status: :unprocessable_entity
-
end
-
else
-
return render json: {errors: [
-
{profile: 'No jobseeker profile exist for this account'},
-
]}, status: :unprocessable_entity
-
end
-
end
-
-
def index
-
@tc = BxBlockProfile::TestScoreAndCourse.all
-
if @tc.present?
-
render json: BxBlockProfile::TestScoreAndCourseSerializer.new(@tc, meta: {
-
message: "List Of Test Score And Courses"
-
}).serializable_hash, status: :ok
-
else
-
render json:{meta: {message: "Record not found."}}
-
end
-
end
-
-
def show
-
test_score = BxBlockProfile::TestScoreAndCourse.find_by({id: params[:id]})
-
-
if test_score.present?
-
render json: BxBlockProfile::TestScoreAndCourseSerializer.new(test_score, meta: {
-
message: "here is the test score for the given id"
-
}).serializable_hash, status: :ok
-
else
-
render json:{meta: {message: "Record not found."}}
-
end
-
end
-
-
def destroy
-
test_score = BxBlockProfile::TestScoreAndCourse.find_by({id: params[:id]})
-
if test_score&.destroy
-
render json:{ meta: { message: "Test Score Removed"}}
-
else
-
render json:{meta: {message: "Record not found."}}
-
end
-
end
-
-
private
-
-
def current_user
-
@account = AccountBlock::Account.find_by(id: @token.id)
-
end
-
-
def test_score_params
-
params.require(:test_score).permit \
-
:title,
-
:associated_with,
-
:score,
-
:test_date,
-
:description,
-
:make_public
-
end
-
end
-
end
-
module BxBlockProfile
-
class ValidationsController < ApplicationController
-
skip_before_action :validate_json_web_token, :only => [:index]
-
-
def index
-
render :json => {
-
:data => [{
-
:email_validation_regexp => email_regex,
-
:password_validation_regexp => password_regex,
-
:password_validation_rules => password_rules,
-
}],
-
}
-
end
-
-
private
-
-
def email_regex
-
AccountBlock::EmailValidation.regex_string
-
end
-
-
def password_regex
-
AccountBlock::PasswordValidation.regex_string
-
end
-
-
def password_rules
-
AccountBlock::PasswordValidation.rules
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
module BxBlockProfileBio
-
# rubocop:disable Style/GuardClause
-
# app/controller/ApplicationCOntroller
-
class ApplicationController < BuilderBase::ApplicationController
-
include BuilderJsonWebToken::JsonWebTokenValidation
-
-
before_action :validate_json_web_token
-
-
rescue_from ActiveRecord::RecordNotFound, with: :not_found
-
-
private
-
-
def not_found
-
render json: { 'errors' => ['Record not found'] }, status: :not_found
-
end
-
-
def current_user
-
@current_user ||= AccountBlock::Account.find(@token.id) if @token.present?
-
end
-
-
def check_account_activated
-
account = AccountBlock::Account.find_by(id: current_user.id)
-
unless account.activated
-
render json: { error: {
-
message: 'Account has been not activated'
-
} }, status: :unprocessable_entity
-
end
-
end
-
end
-
# rubocop:enable Style/GuardClause
-
end
-
# frozen_string_literal: true
-
-
module BxBlockProfileBio
-
# rubocop:disable Metrics/ClassLength, Metrics/AbcSize, Metrics/MethodLength, Style/GuardClause, Lint/RescueException, Lint/UselessAssignment
-
# app/controller/PreferencesController
-
class PreferencesController < ApplicationController
-
before_action :load_basic_profile
-
before_action :load_preference, only: %i[update index reset_preference]
-
before_action :check_account_activated
-
-
def index
-
return if @preference.nil?
-
-
render json: BxBlockProfileBio::PreferenceSerializer.new(@preference).serializable_hash,
-
status: :ok
-
end
-
-
def create
-
return if @account.nil?
-
-
preference = @account.preference
-
-
if preference.present?
-
return render json: { errors: [
-
{ profile: 'Preference has been already created' }
-
] }, status: :unprocessable_entity
-
end
-
create_preference
-
rescue Exception => e
-
render json: { errors: [{ preference: e.message }] },
-
status: :unprocessable_entity
-
end
-
-
def update
-
return if @preference.nil?
-
-
update_result = @preference.update(preference_params)
-
if update_result
-
render json: BxBlockProfileBio::PreferenceSerializer.new(@preference).serializable_hash,
-
status: :ok
-
else
-
render json: { errors: [{ preference: @preference.errors }] },
-
status: :unprocessable_entity
-
end
-
rescue Exception => e
-
render json: { errors: [{ preference: e.message }] },
-
status: :unprocessable_entity
-
end
-
-
def reset_preference
-
return if @preference.nil?
-
-
begin
-
reset_params = {
-
height_range_start: nil, height_range_end: nil, height_type: nil, location: nil, seeking: nil,
-
age_range_start: nil, age_range_end: nil, distance: nil, smoking: nil, drinking: nil, body_type: nil,
-
religion: nil, friend: false, business: false, match_making: false, travel_partner: false, cross_path: false
-
}
-
categories_name = @account.categories.map(&:name)
-
-
arr_hash = {}
-
if categories_name.present?
-
categories_name.each do |category_name|
-
arr_hash[category_name.to_sym.downcase] = true
-
end
-
end
-
reset_params1 = reset_params.merge(arr_hash)
-
-
@preference.update(reset_params1)
-
render json: BxBlockProfileBio::PreferenceSerializer.new(@preference).serializable_hash,
-
status: :ok
-
rescue Exception => e
-
render json: { errors: [{ preference: @preference.message }] },
-
status: :unprocessable_entity
-
end
-
end
-
-
private
-
-
def preference_params
-
params.require(:data)[:attributes].permit \
-
:height_range_start, :height_range_end, :height_type, :location, :seeking,
-
:age_range_start, :age_range_end, :distance, :smoking, :drinking, :body_type,
-
:religion, :friend, :business, :match_making, :travel_partner, :cross_path
-
end
-
-
def create_preference
-
preference = BxBlockProfileBio::Preference.new(preference_params)
-
preference.account_id = @account.id
-
if preference_params[:location].blank?
-
account = AccountBlock::Account.find(current_user.id)
-
location = account.location.as_json || {}
-
preference.location = location['address'] if location.present?
-
end
-
-
if preference.save
-
serializer = BxBlockProfileBio::PreferenceSerializer.new(preference)
-
render json: serializer.serializable_hash,
-
status: :created
-
else
-
render json: { errors: [{ preference: preference.errors }] },
-
status: :unprocessable_entity
-
end
-
end
-
-
def load_basic_profile
-
@account = AccountBlock::Account.find_by(id: current_user.id)
-
-
if @account.nil?
-
render json: {
-
message: 'Account not found'
-
}, status: :not_found
-
end
-
end
-
-
def load_preference
-
@preference = @account.preference
-
-
if @preference.nil?
-
render json: {
-
message: 'Preference not found'
-
}, status: :not_found
-
end
-
end
-
end
-
# rubocop:enable Metrics/ClassLength, Metrics/AbcSize, Metrics/MethodLength, Style/GuardClause, Lint/RescueException, Lint/UselessAssignment
-
end
-
# frozen_string_literal: true
-
-
module BxBlockProfileBio
-
# app/controller/ProfileBiosController
-
class ProfileBiosController < ApplicationController
-
before_action :load_account, only: %i[show]
-
before_action :check_account_activated, only: %i[update show destroy]
-
-
def create
-
profile = BxBlockProfileBio::ProfileBio.includes(:account).find_by(accounts: {id: current_user.id})
-
if profile.present?
-
render json: {errors: [
-
{profile: "Profile bio has been already created"}
-
]}, status: :unprocessable_entity and return
-
end
-
-
begin
-
profile_bio = current_user.build_profile_bio(profile_params)
-
-
if profile_bio.valid? && profile_bio.save
-
render json: BxBlockProfileBio::ProfileBioSerializer.new(profile_bio).serializable_hash, status: :created
-
else
-
render_create_validation_errors(profile_bio)
-
end
-
rescue Exception => e
-
render json: {errors: [e.message]},
-
status: :unprocessable_entity
-
end
-
end
-
-
def update
-
profile =current_user.try(:profile_bio)
-
if profile.nil?
-
render json: {
-
message: "Profile bio doesn't exists"
-
}, status: :not_found and return
-
end
-
-
profile.assign_attributes(profile_params)
-
-
if profile.valid?
-
profile.save
-
update_profile_bio(profile)
-
else
-
render json: {errors: [
-
{profile: profile.errors.full_messages}
-
]}, status: :unprocessable_entity
-
end
-
rescue Exception => e
-
render json: {errors: [e.message]},
-
status: :unprocessable_entity
-
end
-
-
def destroy
-
profile =current_user.try(:profile_bio)
-
if profile.nil?
-
render json: {
-
message: "Profile bio doesn't exists"
-
}, status: :not_found and return
-
elsif profile.destroy!
-
render json: {message: "Deleted Successfully"}, status: :ok
-
end
-
rescue Exception => e
-
render json: {errors: [e.message]},
-
status: :unprocessable_entity
-
end
-
-
def index
-
profile = BxBlockProfileBio::ProfileBio.includes(:account)
-
.find_by(accounts: {id: current_user.id})
-
if profile.nil?
-
render json: {
-
message: "Profile bio doesn't exists"
-
}, status: :not_found and return
-
else
-
render json: BxBlockProfileBio::ProfileBioSerializer.new(profile).serializable_hash, status: :ok
-
end
-
end
-
-
def fetch_interests
-
interests_values = BxBlockProfileBio::ProfileBio::INTERESTS_VALUES
-
if params[:search_item].present?
-
interests_values = interests_values.select { |item| item.downcase.include?(params[:search_item]) }
-
end
-
render json: interests_values,
-
status: :ok
-
end
-
-
def fetch_personalities
-
personalities_values = BxBlockProfileBio::ProfileBio::PERSONALITY_VALUES
-
if params[:search_item].present?
-
personalities_values = personalities_values.select { |item| item.downcase.include?(params[:search_item]) }
-
end
-
render json: personalities_values,
-
status: :ok
-
end
-
-
private
-
-
def update_profile_bio(profile)
-
profile.save
-
render json: BxBlockProfileBio::ProfileBioSerializer.new(profile).serializable_hash, status: :ok
-
end
-
-
def render_create_validation_errors(profile_bio)
-
errors_arr = []
-
errors_arr << profile_bio.errors.full_messages if profile_bio.errors.present?
-
errors_arr << current_user.errors.full_messages if current_user.errors.present?
-
render json: {errors: errors_arr}, status: :unprocessable_entity
-
end
-
-
def profile_params
-
params.require(:data)[:attributes].permit(
-
:height, :weight, :height_type, :weight_type, :body_type, :mother_tougue,
-
:religion, :zodiac, :marital_status, :smoking, :drinking, :looking_for,
-
:about_me, :about_business, :category_id, custom_attributes: {}, languages: [], personality: [],
-
interests: [],
-
educations_attributes: %i[id qualification description year_from year_to _destroy],
-
achievements_attributes: %i[id title achievement_date detail url _destroy],
-
careers_attributes: [:id, :profession, :is_current, :experience_from,
-
:experience_to, :payscale, :company_name, :sector, :_destroy, {
-
accomplishment: []
-
}]
-
)
-
end
-
-
def load_account
-
@account = AccountBlock::Account.find_by(id: params[:id])
-
-
if @account.nil?
-
render json: {
-
message: "Account doesn't exists"
-
}, status: :not_found
-
end
-
end
-
end
-
# rubocop:enable Metrics/ClassLength, Metrics/AbcSize, Naming/MemoizedInstanceVariableName, Metrics/MethodLength, Style/GuardClause, Layout/LineLength, Lint/RescueException
-
end
-
# frozen_string_literal: true
-
-
module BxBlockProfileBio
-
# app/controller/ViewProfilesController
-
# rubocop:disable Metrics/AbcSize, Metrics/MethodLength, Style/GuardClause, , Layout/LineLength, Lint/RescueException
-
class ViewProfilesController < ApplicationController
-
# before_action :load_basic_profile, only: %i[index]
-
before_action :check_account_activated
-
-
def index
-
account = AccountBlock::Account.find_by(id: current_user.id)
-
view_profiles = BxBlockProfileBio::ViewProfile.where(view_by_id: account.id)
-
-
if view_profiles.present?
-
if params[:filter_by].present?
-
case params[:filter_by]
-
when 'newest_first'
-
view_profiles = view_profiles.order('view_profiles.created_at desc')
-
when 'oldest_first'
-
view_profiles = view_profiles.order('view_profiles.created_at asc')
-
end
-
end
-
-
if params[:search_by_name].present?
-
view_profiles = view_profiles.joins(:viewer).where(
-
'accounts.first_name ILIKE ? or accounts.last_name ILIKE ?',
-
"%#{params[:search_by_name]}%", "%#{params[:search_by_name]}%"
-
).distinct
-
end
-
-
BxBlockProfileBio::ViewProfile.mutual_friend(current_user.id, view_profiles)
-
-
json_data = BxBlockProfileBio::ViewProfileSerializer.new(view_profiles).serializable_hash
-
json_data[:total_viewed_count] = begin
-
json_data[:data].count
-
rescue StandardError
-
0
-
end
-
render json: json_data,
-
status: :ok
-
else
-
render json: { message: "view profiles does not found" },
-
status: :not_found
-
end
-
end
-
-
def create
-
view_profile = BxBlockProfileBio::ViewProfile.new(view_profile_params)
-
view_profile.view_by_id = current_user.id
-
-
if view_profile.save
-
serializer = BxBlockProfileBio::ViewProfileSerializer.new(view_profile)
-
render json: serializer.serializable_hash,
-
status: :ok
-
else
-
render json: { errors: [{ view_profile: view_profile.errors }] },
-
status: :unprocessable_entity
-
end
-
end
-
-
private
-
-
def view_profile_params
-
params.require(:data)[:attributes].permit \
-
:account_id, :profile_bio_id, :profile_image
-
end
-
end
-
# rubocop:enable Metrics/AbcSize, Metrics/MethodLength, Style/GuardClause, , Layout/LineLength, Lint/RescueException
-
end
-
module BxBlockPushNotifications
-
class ApplicationController < BuilderBase::ApplicationController
-
include BuilderJsonWebToken::JsonWebTokenValidation
-
-
before_action :validate_json_web_token
-
-
rescue_from ActiveRecord::RecordNotFound, :with => :not_found
-
-
private
-
-
def not_found
-
render :json => {'errors' => ['Record not found']}, :status => :not_found
-
end
-
-
def current_user
-
@current_user ||= AccountBlock::Account.find(@token.id) if @token.present?
-
end
-
-
end
-
end
-
module BxBlockPushNotifications
-
class PushNotificationsController < ApplicationController
-
-
def index
-
push_notifications = current_user.push_notifications
-
serializer = BxBlockPushNotifications::PushNotificationSerializer.new(
-
push_notifications
-
)
-
-
render json: serializer.serializable_hash, status: :ok
-
end
-
-
def create
-
push_notification = BxBlockPushNotifications::PushNotification.new(
-
push_notifications_params.merge({account_id: current_user.id})
-
)
-
if push_notification.save
-
serializer = BxBlockPushNotifications::PushNotificationSerializer.new(push_notification)
-
render json: serializer.serializable_hash, status: :ok
-
else
-
render json: {
-
errors: [{
-
push_notification: push_notification.errors.full_messages
-
}]
-
}, status: :unprocessable_entity
-
end
-
rescue Exception => push_notification
-
render json: {errors: [{push_notification: push_notification.message}]},
-
status: :unprocessable_entity
-
end
-
-
def update
-
push_notification = BxBlockPushNotifications::PushNotification.find_by(
-
id: params[:id], push_notificable_id: current_user.id
-
)
-
return render json: { message: "Not Found" },
-
status: :not_found if push_notification.blank?
-
-
if push_notification.update(push_notifications_params)
-
serializer = BxBlockPushNotifications::PushNotificationSerializer.new(push_notification)
-
render json: serializer.serializable_hash,
-
status: :ok
-
else
-
render json: { errors: [{push_notification: push_notification.errors.full_messages}]},
-
status: :unprocessable_entity
-
end
-
rescue Exception => push_notification
-
render json: {errors: [{push_notification: push_notification.message}]},
-
status: :unprocessable_entity
-
end
-
-
def show
-
push_notification = current_user.push_notifications.find(params[:id])
-
-
if push_notification.blank?
-
render json: { message: "Push Notification Not Found" },
-
status: :not_found
-
else
-
render json: BxBlockPushNotifications::PushNotificationSerializer.new(push_notification)
-
end
-
end
-
-
private
-
-
def push_notifications_params
-
params.require(:data)[:attributes].permit(
-
:push_notificable_id,
-
:push_notificable_type,
-
:remarks, :is_read
-
)
-
end
-
end
-
end
-
module BxBlockRequestManagement
-
class ApplicationController < BuilderBase::ApplicationController
-
include BuilderJsonWebToken::JsonWebTokenValidation
-
-
before_action :validate_json_web_token
-
-
rescue_from ActiveRecord::RecordNotFound, with: :not_found
-
-
private
-
-
def not_found
-
render json: {"errors" => ["Record not found"]}, status: :not_found
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
module BxBlockRequestManagement
-
class RequestsController < ApplicationController
-
include BuilderJsonWebToken::JsonWebTokenValidation
-
before_action :validate_json_web_token
-
-
before_action :load_account
-
before_action :find_reviewer_group, only: :create
-
before_action :find_request, only: %i[update destroy review]
-
-
def index
-
render json: RequestSerializer.new(Request.all).serializable_hash, status: :ok
-
end
-
-
def show
-
request = Request.find_by(id: params[:id])
-
-
if request.present?
-
render json: RequestSerializer.new(request).serializable_hash, status: :ok
-
else
-
render json: { errors: [{ message: 'Request not found' }] }, status: :not_found
-
end
-
end
-
-
def sent
-
requests = Request.where(sender: @current_account)
-
render json: RequestSerializer.new(requests).serializable_hash, status: :ok
-
end
-
-
def received
-
if @current_account.groups.empty?
-
render json: { errors: [{ message: 'Your account is not a part of a group' }] }, status: :not_found and return
-
end
-
-
requests = Request.where(account_group: @current_account.groups)
-
render json: RequestSerializer.new(requests).serializable_hash, status: :ok
-
end
-
-
def create
-
if create_request_params[:request_text].blank?
-
render json: { errors: "Request text can't be blank" }, status: :unprocessable_entity
-
else
-
request = Request.new(
-
sender: @current_account,
-
account_group: @reviewer_group,
-
request_text: create_request_params[:request_text]
-
)
-
-
if request.save
-
render json: RequestSerializer.new(request).serializable_hash, status: :created
-
else
-
render json: { errors: request.errors }, status: :unprocessable_entity
-
end
-
end
-
end
-
-
def destroy
-
return unless check_if_can_review
-
-
if @request.destroy
-
render json: RequestSerializer.new(@request).serializable_hash.merge(
-
{ message: 'Request deleted successfully' }
-
), status: :ok
-
end
-
end
-
-
def update
-
if update_request_params[:request_text].blank?
-
render json: { errors: [{ message: 'Request data is blank' }] }, status: :unprocessable_entity and return
-
else
-
unless @request.sender == @current_account
-
render json: { errors: [{ message: 'Cannot update request that is not yours' }] },
-
status: :forbidden and return
-
end
-
-
unless @request.status == 'rejected'
-
render json: { errors: [{ message: 'Can only update rejected requests' }] },
-
status: :unprocessable_entity and return
-
end
-
-
if @request.update(request_text: update_request_params[:request_text], status: :pending, rejection_reason: nil)
-
render json: RequestSerializer.new(@request).serializable_hash, status: :ok
-
else
-
render json: { errors: @request.errors }, status: :unprocessable_entity
-
end
-
end
-
end
-
-
def review
-
return unless check_if_can_review
-
-
unless @request.status == 'pending'
-
render json: { errors: [{ message: 'Can only review pending requests' }] },
-
status: :unprocessable_entity and return
-
end
-
-
unless [true, false].include? review_params[:is_accepted]
-
render json: { errors: [{ message: 'is_accepted must be either true or false' }] },
-
status: :unprocessable_entity and return
-
end
-
-
unless review_params[:is_accepted] || review_params[:rejection_reason].present?
-
render json: { errors: [{ message: 'Reason for rejection must be given' }] },
-
status: :unprocessable_entity and return
-
end
-
-
if @request.update(
-
status: review_params[:is_accepted] == true ? 'accepted' : 'rejected',
-
rejection_reason: review_params[:is_accepted] == true ? nil : review_params[:rejection_reason]
-
)
-
render json: RequestSerializer.new(@request).serializable_hash, status: :ok
-
else
-
render json: { errors: @request.errors }, status: :unprocessable_entity
-
end
-
end
-
-
private
-
-
def create_request_params
-
params.require(:data).permit \
-
:reviewer_group_id, :request_text
-
end
-
-
def update_request_params
-
params.require(:data).permit \
-
:request_text
-
end
-
-
def review_params
-
params.permit(:is_accepted, :rejection_reason)
-
end
-
-
def find_reviewer_group
-
@reviewer_group = BxBlockAccountGroups::Group.find_by(id: create_request_params[:reviewer_group_id])
-
-
render json: { errors: [{ message: 'Reviewer group not found' }] }, status: :not_found if @reviewer_group.nil?
-
end
-
-
def find_request
-
@request = Request.find_by(id: params[:id])
-
-
render json: { errors: [{ message: 'Request not found' }] }, status: :not_found if @request.nil?
-
end
-
-
def check_if_can_review
-
if @current_account.groups.empty?
-
render json: { errors: [{ message: 'Your account is not a part of a group' }] },
-
status: :not_found and return false
-
end
-
-
unless @current_account.groups.include?(@request.account_group)
-
render json: { errors: [{ message: 'You are not a reviewer of this request' }] },
-
status: :forbidden and return false
-
end
-
-
true
-
end
-
-
def format_activerecord_errors(errors)
-
result = []
-
errors.each do |attribute, error|
-
result << { attribute => error }
-
end
-
result
-
end
-
-
def load_account
-
@current_account = AccountBlock::Account.find_by(id: @token.id)
-
-
if @current_account.nil?
-
render json: { errors: [{ message: "Account with id #{@token.id} doesn't exist" }] }, status: :not_found
-
end
-
end
-
end
-
end
-
module BxBlockRolesPermissions
-
class AccountDetailsController < ApplicationController
-
# protect_from_forgery with: :exception
-
include BuilderJsonWebToken::JsonWebTokenValidation
-
-
before_action :validate_json_web_token, only: [:list_users]
-
-
def list_users
-
@account = AccountBlock::Account.find(@token.id)
-
@accounts = AccountBlock::Account.all
-
if @account.present? && check_admin_auth
-
render json: AccountBlock::AccountSerializer.new(@accounts).serializable_hash, status: :ok
-
else
-
render json: {errors: "account does not have access"}, status: :unauthorized
-
end
-
end
-
-
def check_admin_auth
-
@account.try(:role).try(:name) == "admin"
-
end
-
end
-
end
-
module BxBlockRolesPermissions
-
class ApplicationController < BuilderBase::ApplicationController
-
# protect_from_forgery with: :exception
-
end
-
end
-
module BxBlockSettings
-
class ApplicationController < BuilderBase::ApplicationController
-
# protect_from_forgery with: :exception
-
end
-
end
-
module BxBlockSettings
-
class SettingsController < ApplicationController
-
def index
-
settings = Setting.all
-
render json: { settings: settings, message: 'Successfully loaded' }
-
end
-
end
-
end
-
module BxBlockShoppingCart
-
class ApplicationController < BuilderBase::ApplicationController
-
include BuilderJsonWebToken::JsonWebTokenValidation
-
-
before_action :validate_json_web_token
-
-
rescue_from ActiveRecord::RecordNotFound, with: :not_found
-
-
private
-
-
def not_found
-
render json: {"errors" => ["Record not found"]}, status: :not_found
-
end
-
end
-
end
-
module BxBlockShoppingCart
-
class OrderItemsController < ApplicationController
-
before_action :get_user, only: [:create, :destroy]
-
before_action :find_or_build_order, only: [:create, :destroy]
-
before_action :find_order_item, only: [:destroy]
-
before_action :get_service_provider, only: %i[get_booked_time_slots]
-
-
def create
-
@order_item = @order.order_items.find_by(catalogue_id: params[:order_items][:catalogue_id])
-
-
if @order_item.present?
-
@order_item.update(order_items_params)
-
else
-
@order_item = @order.order_items.create(order_items_params)
-
end
-
if @order_item.errors.present?
-
render json: {
-
errors: format_activerecord_errors(@order_item.errors)
-
}, status: :unprocessable_entity
-
else
-
@order.reload
-
render json: BxBlockShoppingCart::OrderSerializer.new(@order).serializable_hash, status: 201
-
end
-
end
-
-
def destroy
-
if @order_item.destroy
-
@order.reload
-
render json: {message: "Order items deleted succesfully!"}, status: :ok
-
else
-
render json: {
-
errors: format_activerecord_errors(@order_item.errors)
-
}, status: :unprocessable_entity
-
end
-
end
-
-
private
-
-
def order_items_params
-
params.require(:order_items).permit(
-
:catalogue_id, :quantity, :taxable,
-
:taxable_value, :other_charges
-
)
-
end
-
-
def format_activerecord_errors(errors)
-
result = []
-
errors.each do |attribute, error|
-
result << {attribute => error}
-
end
-
result
-
end
-
-
def get_user
-
@customer = AccountBlock::Account.find(@token.id)
-
render json: {errors: "Customer is invalid"} and return unless @customer.present?
-
end
-
-
def find_or_build_order
-
@order = @customer.orders.where.not(status: ["completed", "cancelled"]).first
-
if @order.blank?
-
@order = @customer.orders.create
-
end
-
end
-
-
def find_order_item
-
@order_item = @order.order_items.find(params[:id])
-
end
-
end
-
end
-
module BxBlockShoppingCart
-
class OrdersController < ApplicationController
-
before_action :get_user, only: %i[show create index]
-
before_action :find_order, only: %i[show]
-
-
def index
-
orders = if params[:filter_by].present? && params[:filter_by].downcase == "history"
-
@customer.orders.completed_cancelled
-
elsif params[:filter_by].present?
-
@customer.orders.where(status: params[:filter_by])
-
end
-
render json: {message: "No order present"} and return unless orders.present?
-
render json: BxBlockShoppingCart::OrderSerializer.new(
-
orders
-
).serializable_hash
-
end
-
-
def show
-
render json: BxBlockShoppingCart::OrderSerializer.new(@order)
-
end
-
-
private
-
-
def get_user
-
@customer = AccountBlock::Account.find(@token.id)
-
render json: {errors: "Customer is invalid"} and return unless @customer.present?
-
end
-
-
def find_order
-
@order = @customer.orders.find(params[:id])
-
end
-
end
-
end
-
module BxBlockSplashscreen4
-
class ApplicationController < BuilderBase::ApplicationController
-
include BuilderJsonWebToken::JsonWebTokenValidation
-
-
before_action :validate_json_web_token
-
-
rescue_from ActiveRecord::RecordNotFound, :with => :not_found
-
-
private
-
-
def not_found
-
render :json => {'errors' => ['Record not found']}, :status => :not_found
-
end
-
end
-
end
-
module BxBlockSplitpayments
-
class ApplicationController < BuilderBase::ApplicationController
-
end
-
end
-
module BxBlockSplitpayments
-
class SplitpaymentsController < BxBlockSplitpayments::ApplicationController
-
def split_payment
-
@order = BxBlockShoppingCart::Order.find_by(id: params[:order_id])
-
if !@order.present?
-
return render json: {errors: "Order Not Found"}, status: :unprocessable_entity
-
end
-
if @order.is_split == true
-
return render json: {order_detail: @order}, status: :ok
-
else
-
BxBlockSplitpayments::Order.complete_order(@order)
-
@order = BxBlockShoppingCart::Order.find_by(id: @order.id)
-
return render json: {order_detail: @order}, status: :ok
-
end
-
end
-
end
-
end
-
module BxBlockStripeIntegration
-
class ApplicationController < BuilderBase::ApplicationController
-
include BuilderJsonWebToken::JsonWebTokenValidation
-
-
before_action :validate_json_web_token
-
-
def current_user
-
AccountBlock::Account.find(@token.id)
-
end
-
-
private
-
-
def not_found
-
render json: {"errors" => ["Record not found"]}, status: :not_found
-
end
-
-
def check_create_stripe_customer
-
return if current_user.stripe_id.present?
-
-
stripe_customer = Stripe::Customer.create({email: current_user.email})
-
current_user.update(stripe_id: stripe_customer.id)
-
end
-
-
def validate_parameters(params_to_check, parameter_names)
-
parameter_names.each do |parameter_name|
-
unless params_to_check[parameter_name].present?
-
render json: {
-
errors: [params: "#{parameter_name} is not provided"]
-
}, status: :unprocessable_entity and return false
-
end
-
end
-
end
-
end
-
end
-
module BxBlockStripeIntegration
-
class PaymentMethodsController < BxBlockStripeIntegration::ApplicationController
-
before_action :check_create_stripe_customer, only: [:index, :create]
-
-
def index
-
stripe_payment_methods = Stripe::PaymentMethod.list(customer: current_user.stripe_id, type: "card")
-
payment_methods = []
-
stripe_payment_methods.each do |stripe_pm|
-
payment_methods << PaymentMethod.new(stripe_pm)
-
end
-
render json: PaymentMethodSerializer.new(payment_methods).serializable_hash
-
rescue Stripe::StripeError => e
-
render json: {
-
errors: [{stripe: e.message}]
-
}, status: :unprocessable_entity
-
end
-
-
def create
-
valid, result = CreatePaymentMethod.new(payment_method_params.to_h).call
-
-
if valid
-
valid, result = AttachPaymentMethod.new(current_user.stripe_id, result.id).call
-
if valid
-
render json: PaymentMethodSerializer.new(PaymentMethod.new(result)).serializable_hash
-
else
-
render json: {
-
errors: [{stripe: result}]
-
}, status: :unprocessable_entity
-
end
-
else
-
render json: {
-
errors: [{stripe: result}]
-
}, status: :unprocessable_entity
-
end
-
end
-
-
private
-
-
def check_create_stripe_customer
-
return if current_user.stripe_id.present?
-
-
stripe_customer = Stripe::Customer.create({email: current_user.email})
-
current_user.update(stripe_id: stripe_customer.id)
-
end
-
-
def payment_method_params
-
params.require(:payment_method).permit(:number, :exp_month, :exp_year, :cvc)
-
end
-
end
-
end
-
module BxBlockStripeIntegration
-
class PaymentsController < BxBlockStripeIntegration::ApplicationController
-
before_action :check_create_stripe_customer, :find_currency, only: [:create]
-
-
def create
-
return unless validate_parameters(payment_params, %w[payment_method_id])
-
-
order = BxBlockOrderManagement::Order.find_by_id(payment_params[:order_id])
-
-
if order.present?
-
amount = (order.total.to_f * 100).to_i
-
-
begin
-
stripe_payment_intent = Stripe::PaymentIntent.create(
-
customer: current_user.stripe_id,
-
amount: amount,
-
currency: @brand.currency,
-
payment_method: payment_params[:payment_method_id]
-
)
-
render json: PaymentIntentSerializer.new(PaymentIntent.new(stripe_payment_intent)).serializable_hash
-
rescue Stripe::StripeError => e
-
render json: {errors: [{stripe: e.message}]}, status: :unprocessable_entity
-
end
-
else
-
render json: {errors: [order: "Order Not Found."]}, status: :not_found
-
end
-
end
-
-
def confirm
-
return unless validate_parameters(payment_params, %w[payment_method_id payment_intent_id])
-
-
unless current_user.stripe_id.present?
-
render json: {
-
error: "Customer stripe id is not found"
-
}, status: :not_found and return
-
end
-
-
begin
-
stripe_payment_intent = Stripe::PaymentIntent.confirm(
-
payment_params[:payment_intent_id],
-
{
-
payment_method: payment_params[:payment_method_id],
-
receipt_email: current_user.email
-
}
-
)
-
render json: PaymentIntentSerializer.new(PaymentIntent.new(stripe_payment_intent)).serializable_hash
-
rescue Stripe::StripeError => e
-
render json: {
-
errors: [{stripe: e.message}]
-
}, status: :unprocessable_entity
-
end
-
end
-
-
private
-
-
def payment_params
-
params.require(:payment).permit(:order_id, :payment_method_id, :payment_intent_id)
-
end
-
-
def find_currency
-
@brand = BxBlockCatalogue::Brand.last
-
unless @brand.present? && @brand.currency.present?
-
render json: {
-
error: "Brand with a currency is not set"
-
}, status: :not_found
-
end
-
end
-
end
-
end
-
1
module BxBlockTermsAndConditions
-
1
class ApplicationController < BuilderBase::ApplicationController
-
# include ActionController::RequestForgeryProtection
-
1
include BuilderJsonWebToken::JsonWebTokenValidation
-
# protect_from_forgery with: :null_session
-
-
# before_action :validate_json_web_token
-
-
# rescue_from ActiveRecord::RecordNotFound, with: :not_found
-
-
1
def current_user
-
6
@current_user = AccountBlock::Account.find(@token.id)
-
rescue ActiveRecord::RecordNotFound
-
render json: {errors: [
-
{message: "Please login again."}
-
]}, status: :unprocessable_entity
-
end
-
-
# def admin_auth
-
# current_user.role.present? && current_user.role.name.eql?("group_admin") ? "true" : "false"
-
# end
-
-
# def basic_auth
-
# current_user.role.present? && current_user.role.name.eql?("group_basic") ? "true" : "false"
-
# end
-
-
# def account_auth
-
# current_user.id.eql?(params[:account_id].to_i) ? "true" : "false"
-
# end
-
-
1
private
-
-
1
def not_found
-
render json: {"errors" => ["Record not found"]}, status: :not_found
-
end
-
end
-
end
-
1
module BxBlockTermsAndConditions
-
1
class TermsAndConditionsController < ApplicationController
-
1
before_action :validate_json_web_token, :current_user, only: [:accept_and_reject]
-
-
# def create
-
# term = BxBlockTermsAndConditions::TermsAndCondition.new(terms_and_condition_params
-
# .merge(account_id: current_user.id))
-
# if term.save
-
# render json: {data: {id: term.id}}, status: :created
-
# else
-
# render json: {errors: term.errors}, status: :unprocessable_entity
-
# end
-
# end
-
-
# def index
-
# terms = BxBlockTermsAndConditions::TermsAndCondition.all.select(:id, :created_at, :description)
-
# if terms.present?
-
# render json: {data: terms}, status: :ok
-
# else
-
# render json: {message: "terms and conditions data not found"}, status: :not_found
-
# end
-
# end
-
-
1
def show
-
2
term = BxBlockTermsAndConditions::TermsAndCondition.last
-
2
if term.present?
-
1
render json: TermsAndConditionsSerializer.new(term)
-
.serializable_hash, status: :ok
-
else
-
1
render json: {message: "terms and conditions data not found"}, status: :not_found
-
end
-
end
-
-
1
def latest_record
-
2
account = AccountBlock::Account.find(params[:id])
-
2
term = BxBlockTermsAndConditions::TermsAndCondition.last
-
2
if term.present? && account.present?
-
1
user_term = BxBlockTermsAndConditions::UserTermAndCondition.find_or_create_by(terms_and_condition_id: term.id, account_id: account.id)
-
1
if update_params[:is_accepted] == "true"
-
if user_term.present?
-
user_term.update(is_accepted: update_params[:is_accepted], account_id: account.id)
-
render json: {data: {user_term: user_term }, message: "Terms and Conditions retrieved successfully!"}.as_json.merge({step: 3}), status: :ok
-
else
-
user_term = BxBlockTermsAndConditions::UserTermAndCondition.create(terms_and_condition_id: term.id, account_id: account.id, is_accepted: update_params[:is_accepted])
-
render json: {data: {user_term: user_term }, message: "Terms and Conditions retrieved successfully!"}.as_json.merge({step: 3}), status: :created
-
end
-
else
-
1
render json: {message: "Please accept terms and condition to move ahead"}, status: :unprocessable_entity
-
end
-
else
-
1
render json: {message: "terms and conditions data not found"}, status: :not_found
-
end
-
end
-
-
1
def accept_and_reject
-
4
term = BxBlockTermsAndConditions::TermsAndCondition.last
-
4
if term.present?
-
3
@user_term = BxBlockTermsAndConditions::UserTermAndCondition.find_or_create_by(terms_and_condition_id: term.id)
-
3
if update_params[:is_accepted] == "true" || update_params[:is_accepted] == "false"
-
2
if @user_term.present?
-
2
@user_term.update(is_accepted: update_params[:is_accepted], account_id: current_user.id)
-
else
-
@user_term = BxBlockTermsAndConditions::UserTermAndCondition.create!(terms_and_condition_id: term.id, account_id: current_user.id, is_accepted: update_params[:is_accepted])
-
end
-
2
render json: @user_term, status: :created
-
else
-
1
render json: {message: "is_accepted should be either true or false."}, status: :unprocessable_entity
-
end
-
else
-
1
render json: {message: "Terms and Condition not found"}, status: :not_found
-
end
-
end
-
-
1
private
-
-
# def check_admin
-
# if admin_auth.eql?("true") || account_auth.eql?("true")
-
# true
-
# else
-
# render json: {message: "You are not authorised user or proper role admin"}, status: :unauthorized
-
# end
-
# end
-
-
# def check_basic
-
# if account_auth.eql?("true")
-
# true
-
# else
-
# render json: {message: "You are not authorised user or proper role basic"}, status: :unauthorized
-
# end
-
# end
-
-
-
# def invalid_id?(id)
-
# id <= 0 || !id.present? ? true : false
-
# end
-
-
# def terms_and_condition_params
-
# params.require(:terms_and_condition).permit(:description)
-
# end
-
-
1
def update_params
-
8
params.require(:data).permit(:is_accepted)
-
end
-
end
-
end
-
module BxBlockWordlookup2
-
class ApplicationController < BuilderBase::ApplicationController
-
include BuilderJsonWebToken::JsonWebTokenValidation
-
-
before_action :validate_json_web_token
-
-
rescue_from ActiveRecord::RecordNotFound, :with => :not_found
-
-
private
-
-
def not_found
-
render :json => {'errors' => ['Record not found']}, :status => :not_found
-
end
-
end
-
end
-
1
module BxBlockElasticsearch::ArticlesHelper
-
end
-
1
module BxBlockElasticsearch::SearchHelper
-
end
-
1
module BxBlockPayments
-
1
module ApplicationHelper
-
end
-
end
-
# frozen_string_literal: true
-
-
1
module BxBlockProfileBio
-
# Application helper
-
1
module ApplicationHelper
-
end
-
end
-
1
module BxBlockStripeIntegration
-
1
module ApplicationHelper
-
end
-
end
-
1
module BxBlockTermsAndConditions
-
1
module ApplicationHelper
-
end
-
end
-
module AccountBlock
-
class ApplicationJob < BuilderBase::ApplicationJob
-
end
-
end
-
class ApplicationJob < ActiveJob::Base
-
# Automatically retry jobs that encountered a deadlock
-
# retry_on ActiveRecord::Deadlocked
-
-
# Most jobs are safe to ignore if the underlying records are no longer available
-
# discard_on ActiveJob::DeserializationError
-
end
-
module BuilderBase
-
class ApplicationJob < ::ApplicationJob
-
end
-
end
-
module BxBlockAccountGroups
-
class ApplicationJob < BuilderBase::ApplicationJob
-
end
-
end
-
module BxBlockAddress
-
class ApplicationJob < BuilderBase::ApplicationJob
-
end
-
end
-
module BxBlockAdmin
-
class ApplicationJob < BuilderBase::ApplicationJob
-
end
-
end
-
module BxBlockAnalytics7
-
class ApplicationJob < BuilderBase::ApplicationJob
-
end
-
end
-
module BxBlockAnnotations
-
class ApplicationJob < BuilderBase::ApplicationJob
-
end
-
end
-
module BxBlockAppointmentManagement
-
class ApplicationJob < BuilderBase::ApplicationJob
-
end
-
end
-
module BxBlockAttachment
-
class ApplicationJob < BuilderBase::ApplicationJob
-
end
-
end
-
# frozen_string_literal: true
-
-
module BxBlockBulkUploading
-
class ApplicationJob < BuilderBase::ApplicationJob
-
end
-
end
-
module BxBlockCatalogue
-
class ApplicationJob < BuilderBase::ApplicationJob
-
end
-
end
-
# frozen_string_literal: true
-
-
module BxBlockCategories
-
class ApplicationJob < BuilderBase::ApplicationJob
-
end
-
end
-
module BxBlockCfhighlightingandunderliningtext
-
class ApplicationJob < BuilderBase::ApplicationJob
-
end
-
end
-
# frozen_string_literal: true
-
-
module BxBlockComments
-
class ApplicationJob < BuilderBase::ApplicationJob
-
end
-
end
-
module BxBlockContactUs
-
class ApplicationJob < BuilderBase::ApplicationJob
-
end
-
end
-
module BxBlockContentManagement
-
class ApplicationJob < BuilderBase::ApplicationJob
-
end
-
end
-
module BxBlockCors
-
class ApplicationJob < BuilderBase::ApplicationJob
-
end
-
end
-
module BxBlockCouponCg
-
class ApplicationJob < BuilderBase::ApplicationJob
-
end
-
end
-
module BxBlockDashboard
-
class ApplicationJob < BuilderBase::ApplicationJob
-
end
-
end
-
module BxBlockDashboardguests
-
class ApplicationJob < BuilderBase::ApplicationJob
-
end
-
end
-
module BxBlockDatastorage
-
class ApplicationJob < BuilderBase::ApplicationJob
-
end
-
end
-
module BxBlockDocumentopener2
-
class ApplicationJob < BuilderBase::ApplicationJob
-
end
-
end
-
module BxBlockDocumentstorage2
-
class ApplicationJob < BuilderBase::ApplicationJob
-
end
-
end
-
module BxBlockDownload
-
class ApplicationJob < BuilderBase::ApplicationJob
-
end
-
end
-
module BxBlockElasticsearch
-
class ApplicationJob < BuilderBase::ApplicationJob
-
end
-
end
-
module BxBlockFavourites
-
class ApplicationJob < BuilderBase::ApplicationJob
-
end
-
end
-
module BxBlockFedexIntegration
-
class ApplicationJob < BuilderBase::ApplicationJob
-
end
-
end
-
module BxBlockForgotPassword
-
class ApplicationJob < BuilderBase::ApplicationJob
-
end
-
end
-
module BxBlockInvoice
-
class ApplicationJob < BuilderBase::ApplicationJob
-
end
-
end
-
module BxBlockLandingpage2
-
class ApplicationJob < BuilderBase::ApplicationJob
-
end
-
end
-
module BxBlockLike
-
class ApplicationJob < BuilderBase::ApplicationJob
-
end
-
end
-
module BxBlockLocation
-
class ApplicationJob < BuilderBase::ApplicationJob
-
end
-
end
-
module BxBlockLogin
-
class ApplicationJob < BuilderBase::ApplicationJob
-
end
-
end
-
module BxBlockMultipageforms2
-
class ApplicationJob < BuilderBase::ApplicationJob
-
end
-
end
-
module BxBlockNavmenu
-
class ApplicationJob < BuilderBase::ApplicationJob
-
end
-
end
-
module BxBlockOfflinebrowsing2
-
class ApplicationJob < BuilderBase::ApplicationJob
-
end
-
end
-
# frozen_string_literal: true
-
-
module BxBlockOrderManagement
-
class ApplicationJob < BuilderBase::ApplicationJob
-
end
-
end
-
module BxBlockPayments
-
class ApplicationJob < ActiveJob::Base
-
end
-
end
-
module BxBlockPlan
-
class ApplicationJob < BuilderBase::ApplicationJob
-
end
-
end
-
module BxBlockPosts
-
class ApplicationJob < BuilderBase::ApplicationJob
-
end
-
end
-
module BxBlockProfile
-
class ApplicationJob < BuilderBase::ApplicationJob
-
end
-
end
-
# frozen_string_literal: true
-
-
module BxBlockProfileBio
-
class ApplicationJob < ActiveJob::Base
-
end
-
end
-
module BxBlockPushNotifications
-
class ApplicationJob < BuilderBase::ApplicationJob
-
end
-
end
-
module BxBlockRequestManagement
-
class ApplicationJob < BuilderBase::ApplicationJob
-
end
-
end
-
module BxBlockRolesPermissions
-
class ApplicationJob < BuilderBase::ApplicationJob
-
end
-
end
-
module BxBlockSettings
-
class ApplicationJob < BuilderBase::ApplicationJob
-
end
-
end
-
module BxBlockShoppingCart
-
class ApplicationJob < BuilderBase::ApplicationJob
-
end
-
end
-
module BxBlockSplashscreen4
-
class ApplicationJob < BuilderBase::ApplicationJob
-
end
-
end
-
module BxBlockSplitpayments
-
class ApplicationJob < BuilderBase::ApplicationJob
-
end
-
end
-
module BxBlockStripeIntegration
-
class ApplicationJob < ActiveJob::Base
-
end
-
end
-
module BxBlockTermsAndConditions
-
class ApplicationJob < ActiveJob::Base
-
end
-
end
-
module BxBlockWordlookup2
-
class ApplicationJob < BuilderBase::ApplicationJob
-
end
-
end
-
1
module AccountBlock
-
1
class AdminUserMailer < ApplicationMailer
-
1
def admin_permission_email
-
160
@account = params[:account]
-
160
@host = Rails.env.development? ? "http://localhost:3000": ENV['HOST_URL']
-
-
160
token = encoded_token
-
160
to_email = @account.email
-
160
@url = "#{@host}/account/accounts/email_confirmation?token=#{token}"
-
160
mail(
-
to: to_email,
-
from: "builder.bx_dev@engineer.ai",
-
subject: "Access Permission"
-
) do |format|
-
320
format.html { render "admin_permission_email" }
-
end
-
end
-
-
1
private
-
-
1
def encoded_token
-
160
BuilderJsonWebToken.encode @account.id, 10.minutes.from_now
-
end
-
end
-
end
-
1
module AccountBlock
-
1
class ApplicationMailer < BuilderBase::ApplicationMailer
-
1
default from: "from@example.com"
-
1
layout "mailer"
-
end
-
end
-
1
module AccountBlock
-
1
class EmailValidationMailer < ApplicationMailer
-
1
def activation_email
-
590
@account = params[:account]
-
590
@host = Rails.env.development? ? "http://localhost:3000": ENV['HOST_URL']
-
-
590
token = encoded_token
-
590
to_email = @account.email || @account.guardian_email
-
590
@url = "#{@host}/account/accounts/email_confirmation?token=#{token}"
-
-
590
mail(
-
to: to_email,
-
from: "builder.bx_dev@engineer.ai",
-
subject: "Account activation"
-
) do |format|
-
1180
format.html { render "activation_email" }
-
end
-
end
-
-
1
private
-
-
1
def encoded_token
-
590
BuilderJsonWebToken.encode @account.id, 10.minutes.from_now
-
end
-
end
-
end
-
1
class ApplicationMailer < ActionMailer::Base
-
1
default from: 'from@example.com'
-
1
layout 'mailer'
-
end
-
1
module BuilderBase
-
1
class ApplicationMailer < ::ApplicationMailer
-
1
default from: 'from@example.com'
-
1
layout 'mailer'
-
end
-
end
-
module BxBlockAccountGroups
-
class ApplicationMailer < BuilderBase::ApplicationMailer
-
default from: "from@example.com"
-
layout "mailer"
-
end
-
end
-
module BxBlockAddress
-
class ApplicationMailer < BuilderBase::ApplicationMailer
-
default from: "from@example.com"
-
layout "mailer"
-
end
-
end
-
module BxBlockAdmin
-
class ApplicationMailer < BuilderBase::ApplicationMailer
-
default from: 'from@example.com'
-
layout 'mailer'
-
end
-
end
-
module BxBlockAnalytics7
-
class ApplicationMailer < BuilderBase::ApplicationMailer
-
default from: 'from@example.com'
-
layout 'mailer'
-
end
-
end
-
module BxBlockAnnotations
-
class ApplicationMailer < BuilderBase::ApplicationMailer
-
default from: 'from@example.com'
-
layout 'mailer'
-
end
-
end
-
module BxBlockAppointmentManagement
-
class ApplicationMailer < BuilderBase::ApplicationMailer
-
default from: "from@example.com"
-
layout "mailer"
-
end
-
end
-
module BxBlockAttachment
-
class ApplicationMailer < BuilderBase::ApplicationMailer
-
default from: 'from@example.com'
-
layout 'mailer'
-
end
-
end
-
# frozen_string_literal: true
-
-
module BxBlockBulkUploading
-
class ApplicationMailer < BuilderBase::ApplicationMailer
-
default from: "from@example.com"
-
layout "mailer"
-
end
-
end
-
module BxBlockCatalogue
-
class ApplicationMailer < BuilderBase::ApplicationMailer
-
default from: "from@example.com"
-
layout "mailer"
-
end
-
end
-
# frozen_string_literal: true
-
-
module BxBlockCategories
-
class ApplicationMailer < BuilderBase::ApplicationMailer
-
default from: "from@example.com"
-
layout "mailer"
-
end
-
end
-
module BxBlockCfhighlightingandunderliningtext
-
class ApplicationMailer < BuilderBase::ApplicationMailer
-
default from: 'from@example.com'
-
layout 'mailer'
-
end
-
end
-
# frozen_string_literal: true
-
-
module BxBlockComments
-
class ApplicationMailer < BuilderBase::ApplicationMailer
-
default from: "from@example.com"
-
layout "mailer"
-
end
-
end
-
module BxBlockContactUs
-
class ApplicationMailer < BuilderBase::ApplicationMailer
-
default from: 'from@example.com'
-
layout 'mailer'
-
end
-
end
-
module BxBlockContentManagement
-
class ApplicationMailer < BuilderBase::ApplicationMailer
-
default from: 'from@example.com'
-
layout 'mailer'
-
end
-
end
-
module BxBlockContentManagement
-
class ContentMailer < ApplicationMailer
-
end
-
end
-
module BxBlockCors
-
class ApplicationMailer < BuilderBase::ApplicationMailer
-
default from: 'from@example.com'
-
layout 'mailer'
-
end
-
end
-
module BxBlockCouponCg
-
class ApplicationMailer < BuilderBase::ApplicationMailer
-
default from: 'from@example.com'
-
layout 'mailer'
-
end
-
end
-
module BxBlockDashboard
-
class ApplicationMailer < BuilderBase::ApplicationMailer
-
default from: 'from@example.com'
-
layout 'mailer'
-
end
-
end
-
module BxBlockDashboardguests
-
class ApplicationMailer < BuilderBase::ApplicationMailer
-
default from: 'from@example.com'
-
layout 'mailer'
-
end
-
end
-
module BxBlockDatastorage
-
class ApplicationMailer < BuilderBase::ApplicationMailer
-
default from: 'from@example.com'
-
layout 'mailer'
-
end
-
end
-
module BxBlockDocumentopener2
-
class ApplicationMailer < BuilderBase::ApplicationMailer
-
default from: 'from@example.com'
-
layout 'mailer'
-
end
-
end
-
module BxBlockDocumentstorage2
-
class ApplicationMailer < BuilderBase::ApplicationMailer
-
default from: 'from@example.com'
-
layout 'mailer'
-
end
-
end
-
module BxBlockDownload
-
class ApplicationMailer < BuilderBase::ApplicationMailer
-
default from: 'from@example.com'
-
layout 'mailer'
-
end
-
end
-
module BxBlockElasticsearch
-
class ApplicationMailer < BuilderBase::ApplicationMailer
-
default from: 'from@example.com'
-
layout 'mailer'
-
end
-
end
-
module BxBlockFavourites
-
class ApplicationMailer < BuilderBase::ApplicationMailer
-
default from: "from@example.com"
-
layout "mailer"
-
end
-
end
-
module BxBlockFedexIntegration
-
class ApplicationMailer < BuilderBase::ApplicationMailer
-
default from: 'from@example.com'
-
layout 'mailer'
-
end
-
end
-
1
module BxBlockForgotPassword
-
1
class ApplicationMailer < BuilderBase::ApplicationMailer
-
1
default from: 'from@example.com'
-
1
layout 'mailer'
-
end
-
end
-
1
module BxBlockForgotPassword
-
1
class EmailOtpMailer < ApplicationMailer
-
1
def otp_email
-
3
if params[:incoming_params][:data][:type] == 'Student'
-
@account = AccountBlock::Account.find_by(student_unique_id: params[:incoming_params][:data][:unique_id])
-
else
-
3
@account = AccountBlock::Account.find_by(email: params[:otp].email)
-
end
-
3
@otp = params[:otp]
-
3
@host = Rails.env.development? ? 'http://localhost:3000' : params[:host]
-
3
mail(
-
to: @otp.email,
-
from: 'builder.bx_dev@engineer.ai',
-
subject: 'Your OTP code') do |format|
-
6
format.html { render 'otp_email' }
-
end
-
end
-
end
-
end
-
module BxBlockInvoice
-
class ApplicationMailer < BuilderBase::ApplicationMailer
-
default from: "from@example.com"
-
layout "mailer"
-
end
-
end
-
module BxBlockLandingpage2
-
class ApplicationMailer < BuilderBase::ApplicationMailer
-
default from: 'from@example.com'
-
layout 'mailer'
-
end
-
end
-
module BxBlockLike
-
class ApplicationMailer < BuilderBase::ApplicationMailer
-
default from: "from@example.com"
-
layout "mailer"
-
end
-
end
-
module BxBlockLocation
-
class ApplicationMailer < BuilderBase::ApplicationMailer
-
default from: 'from@example.com'
-
layout 'mailer'
-
end
-
end
-
module BxBlockLogin
-
class ApplicationMailer < BuilderBase::ApplicationMailer
-
default from: 'from@example.com'
-
layout 'mailer'
-
end
-
end
-
module BxBlockMultipageforms2
-
class ApplicationMailer < BuilderBase::ApplicationMailer
-
default from: 'from@example.com'
-
layout 'mailer'
-
end
-
end
-
module BxBlockNavmenu
-
class ApplicationMailer < BuilderBase::ApplicationMailer
-
default from: 'from@example.com'
-
layout 'mailer'
-
end
-
end
-
module BxBlockOfflinebrowsing2
-
class ApplicationMailer < BuilderBase::ApplicationMailer
-
default from: 'from@example.com'
-
layout 'mailer'
-
end
-
end
-
# frozen_string_literal: true
-
-
module BxBlockOrderManagement
-
class ApplicationMailer < BuilderBase::ApplicationMailer
-
default from: "from@example.com"
-
layout "mailer"
-
end
-
end
-
module BxBlockPayments
-
class ApplicationMailer < ActionMailer::Base
-
default from: 'from@example.com'
-
layout 'mailer'
-
end
-
end
-
module BxBlockPlan
-
class ApplicationMailer < BuilderBase::ApplicationMailer
-
default from: 'from@example.com'
-
layout 'mailer'
-
end
-
end
-
module BxBlockPosts
-
class ApplicationMailer < BuilderBase::ApplicationMailer
-
default from: 'from@example.com'
-
layout 'mailer'
-
end
-
end
-
module BxBlockProfile
-
class ApplicationMailer < BuilderBase::ApplicationMailer
-
default from: 'from@example.com'
-
layout 'mailer'
-
end
-
end
-
# frozen_string_literal: true
-
-
module BxBlockProfileBio
-
class ApplicationMailer < BuilderBase::ApplicationMailer
-
default from: 'from@example.com'
-
layout 'mailer'
-
end
-
end
-
module BxBlockPushNotifications
-
class ApplicationMailer < BuilderBase::ApplicationMailer
-
default from: 'from@example.com'
-
layout 'mailer'
-
end
-
end
-
module BxBlockRequestManagement
-
class ApplicationMailer < BuilderBase::ApplicationMailer
-
default from: "from@example.com"
-
layout "mailer"
-
end
-
end
-
module BxBlockRolesPermissions
-
class ApplicationMailer < BuilderBase::ApplicationMailer
-
default from: "from@example.com"
-
layout "mailer"
-
end
-
end
-
module BxBlockSettings
-
class ApplicationMailer < BuilderBase::ApplicationMailer
-
default from: 'from@example.com'
-
layout 'mailer'
-
end
-
end
-
module BxBlockShoppingCart
-
class ApplicationMailer < BuilderBase::ApplicationMailer
-
default from: "from@example.com"
-
layout "mailer"
-
end
-
end
-
module BxBlockSplashscreen4
-
class ApplicationMailer < BuilderBase::ApplicationMailer
-
default from: 'from@example.com'
-
layout 'mailer'
-
end
-
end
-
module BxBlockSplitpayments
-
class ApplicationMailer < BuilderBase::ApplicationMailer
-
default from: 'from@example.com'
-
layout 'mailer'
-
end
-
end
-
module BxBlockStripeIntegration
-
class ApplicationMailer < ActionMailer::Base
-
default from: "from@example.com"
-
layout "mailer"
-
end
-
end
-
module BxBlockTermsAndConditions
-
class ApplicationMailer < ActionMailer::Base
-
default from: "from@example.com"
-
layout "mailer"
-
end
-
end
-
module BxBlockWordlookup2
-
class ApplicationMailer < BuilderBase::ApplicationMailer
-
default from: 'from@example.com'
-
layout 'mailer'
-
end
-
end
-
1
class Ability
-
1
include CanCan::Ability
-
1
SCHOOL_ADMIN = "School Admin"
-
1
PUBLISHER = "Publisher"
-
1
def initialize(user)
-
117
user ||= AdminUser.new
-
117
if user.super_admin?
-
95
can :manage, :all
-
else
-
-
22
can :read, ActiveAdmin::Page, name: "Dashboard", namespace_name: "admin"
-
# can :read, ActiveAdmin::Page, name: "Analytics", namespace_name: "admin"
-
22
if user.school_allow == true
-
can :read, BxBlockCategories::School, id: user.school_id
-
end
-
22
if user.class_allow == true
-
7
can :manage, BxBlockCategories::SchoolClass
-
7
can :manage, BxBlockCategories::ClassDivision
-
end
-
22
if user.subject_allow == true
-
4
can :manage, BxBlockCatalogue::SubjectManagement
-
end
-
22
if user.assignment_allow == true
-
can :manage, BxBlockCatalogue::Assignment
-
end
-
22
if user.video_allow == true
-
8
can :manage, BxBlockCatalogue::VideosLecture
-
end
-
-
22
if user.account_allow == true
-
can :manage, AccountBlock::Account
-
cannot :manage, AccountBlock::Account, role: { name: [PUBLISHER, SCHOOL_ADMIN] }
-
end
-
end
-
end
-
end
-
-
1
require 'searchkick'
-
1
module AccountBlock
-
1
class Account < AccountBlock::ApplicationRecord
-
1
ActiveSupport.run_load_hooks(:account, self)
-
1
self.table_name = :accounts
-
1
include Searchkick
-
-
1
include Wisper::Publisher
-
-
42
validates :pin, format: { with: /\A\d{4}\z/, message: "must be a 4-digit integer" }, on: :update, if: Proc.new{|object| object.pin.present?}
-
-
1
EMAIL_REGEX = /\w+@\w+.{1}[a-zA-Z]{2,}/
-
-
# before_validation :valid_phone_number
-
1
has_one_attached :photo
-
1
before_create :generate_api_key
-
1
has_one :blacklist_user, class_name: "AccountBlock::BlackListUser", dependent: :destroy
-
1
has_many :user_terms_and_conditions,
-
class_name: "BxBlockTermsAndConditions::UserTermAndCondition",
-
dependent: :destroy, foreign_key: :account_id
-
1
has_many :terms_and_conditions, through: :user_terms_and_conditions
-
1
after_save :set_black_listed_user
-
1
belongs_to :role, class_name: "BxBlockRolesPermissions::Role"
-
1
belongs_to :school, class_name: "BxBlockCategories::School", optional: true
-
1
has_one :profile, class_name: "BxBlockProfile::Profile", dependent: :destroy
-
1
has_many :subjects, class_name: "BxBlockCatalogue::Subject"
-
1
belongs_to :class_division, class_name: "BxBlockCategories::ClassDivision", optional: true
-
1
has_many :subject_managements, class_name: "BxBlockCatalogue::SubjectManagement"
-
-
1
has_many :ebook_allotments, class_name: "BxBlockBulkUploading::EbookAllotment", foreign_key: "account_id"
-
1
has_many :ebooks, class_name: "BxBlockBulkUploading::Ebook",through: :ebook_allotments
-
-
1
enum status: %i[regular suspended deleted]
-
1
enum user_type: {student: 'Student', teacher: 'Teacher', publisher: 'Publisher', school_admin: 'School Admin'}
-
-
1
scope :active, -> { where(activated: true) }
-
1
scope :existing_accounts, -> { where(status: ["regular", "suspended"]) }
-
-
1
validates_presence_of :first_name, :full_phone_number
-
640
validates_presence_of :email, if: Proc.new{|obj| ["Publisher", "Teacher", "School Admin"].include?(obj&.role&.name)}
-
637
validates_presence_of :guardian_email, if: Proc.new{|obj| obj&.role&.name == "Student"}
-
-
640
validates_format_of :email, with: EMAIL_REGEX, if: Proc.new{|obj| obj.email.present?}
-
637
validates_format_of :guardian_email, with: EMAIL_REGEX, if: Proc.new{|obj| obj.guardian_email.present?}
-
640
validates_uniqueness_of :email, if: Proc.new{|obj| obj.email.present?}
-
637
validates_uniqueness_of :bank_account_number, if: Proc.new{|obj| obj.bank_account_number.present?}
-
635
validates_presence_of :student_unique_id, if: Proc.new{|obj| obj.role&.name == "Student"}
-
635
validates_presence_of :teacher_unique_id, if: Proc.new{|obj| obj.role&.name == "Teacher"}
-
635
validates :teacher_unique_id, uniqueness: {scope: :school_id}, if: Proc.new{|obj| obj.teacher_unique_id.present?}
-
# validates_uniqueness_of :guardian_email, if: Proc.new{|object| object.guardian_email.present?}
-
635
validates :student_unique_id, uniqueness: {scope: :school_id}, if: Proc.new{|obj| obj.student_unique_id.present?}
-
1
validates_length_of :full_phone_number, is: 10
-
637
validates_format_of :ifsc_code, with: /\A[a-zA-Z0-9]+\z/, if: Proc.new{|object| object&.role&.name == "Publisher"}
-
637
validates :bank_account_number, numericality: {only_numeric: true}, if: Proc.new{|object| object&.role&.name == "Publisher"}
-
637
validates_length_of :bank_account_number, maximum: 20, if: Proc.new{|object| object&.role&.name == "Publisher"}
-
637
validates_length_of :ifsc_code, maximum: 15, if: Proc.new{|object| object&.role&.name == "Publisher"}
-
-
1
private
-
-
# def parse_full_phone_number
-
# phone = Phonelib.parse(full_phone_number)
-
# self.full_phone_number = phone.sanitized
-
# self.country_code = phone.country_code
-
# self.phone_number = phone.raw_national
-
# end
-
-
# def valid_phone_number
-
# unless Phonelib.valid?(full_phone_number)
-
# errors.add(:full_phone_number, "Invalid or Unrecognized Phone Number")
-
# end
-
# end
-
-
1
after_create :send_mail
-
-
1
def send_mail
-
590
AccountBlock::EmailValidationMailer
-
.with(account: self)
-
.activation_email.deliver
-
end
-
-
1
def generate_api_key
-
590
loop do
-
590
@token = SecureRandom.base64.tr("+/=", "Qrt")
-
590
break @token unless Account.exists?(unique_auth_id: @token)
-
end
-
590
self.unique_auth_id = @token
-
end
-
-
1
def set_black_listed_user
-
622
if is_blacklisted_previously_changed?
-
if is_blacklisted
-
AccountBlock::BlackListUser.create(account_id: id)
-
else
-
blacklist_user.destroy
-
end
-
end
-
end
-
end
-
end
-
1
module AccountBlock
-
1
class ApplicationRecord < BuilderBase::ApplicationRecord
-
1
self.abstract_class = true
-
end
-
end
-
module AccountBlock
-
class BlackListUser < AccountBlock::ApplicationRecord
-
self.table_name = :black_list_users
-
belongs_to :account, class_name: "AccountBlock::Account"
-
-
def user_mobile_number
-
account.full_phone_number
-
end
-
-
def user_email
-
account.email
-
end
-
-
def user_type
-
account.user_type
-
end
-
end
-
end
-
module AccountBlock
-
class EmailAccount < Account
-
ActiveSupport.run_load_hooks(:email_account, self)
-
include Wisper::Publisher
-
validates :email, presence: true
-
end
-
end
-
1
module AccountBlock
-
1
class EmailOtp < ApplicationRecord
-
1
include Wisper::Publisher
-
-
1
self.table_name = :email_otps
-
-
1
validate :valid_email
-
1
validates :email, presence: true
-
-
1
before_create :generate_pin_and_valid_date
-
-
1
attr_reader :phone
-
-
1
def generate_pin_and_valid_date
-
3
self.pin = rand(1_000..9_999)
-
3
self.valid_until = Time.current + 5.minutes
-
end
-
-
1
private
-
-
1
def valid_email
-
3
unless URI::MailTo::EMAIL_REGEXP.match?(email)
-
errors.add(:full_phone_number, "Invalid email format")
-
end
-
end
-
end
-
end
-
module AccountBlock
-
class SmsAccount < Account
-
include Wisper::Publisher
-
validates :full_phone_number, uniqueness: true, presence: true
-
end
-
end
-
module AccountBlock
-
class SmsOtp < ApplicationRecord
-
self.table_name = :sms_otps
-
-
include Wisper::Publisher
-
-
before_validation :parse_full_phone_number
-
-
before_create :generate_pin_and_valid_date
-
after_create :send_pin_via_sms
-
-
validate :valid_phone_number
-
validates :full_phone_number, presence: true
-
-
attr_reader :phone
-
-
def generate_pin_and_valid_date
-
self.pin = rand(1_000..9_999)
-
self.valid_until = Time.current + 5.minutes
-
end
-
-
def send_pin_via_sms
-
message = "Your Pin Number is #{pin}"
-
txt = BxBlockSms::SendSms.new("+#{full_phone_number}", message)
-
txt.call
-
end
-
-
private
-
-
def parse_full_phone_number
-
@phone = Phonelib.parse(full_phone_number)
-
self.full_phone_number = @phone.sanitized
-
end
-
-
def valid_phone_number
-
unless Phonelib.valid?(full_phone_number)
-
errors.add(:full_phone_number, "Invalid or Unrecognized Phone Number")
-
end
-
end
-
end
-
end
-
module AccountBlock
-
class SocialAccount < Account
-
include Wisper::Publisher
-
-
validates :email, uniqueness: true, presence: true
-
validates :unique_auth_id, presence: true
-
-
after_validation :set_active
-
-
def set_active
-
self.activated = true
-
end
-
end
-
end
-
1
class AdminUser < ApplicationRecord
-
# Include default devise modules. Others available are:
-
# :confirmable, :lockable, :timeoutable, :trackable and :omniauthable
-
1
devise :database_authenticatable,
-
:recoverable, :rememberable, :validatable
-
-
1
enum role: [:super_admin, :sub_admin]
-
1
validates_presence_of :role
-
-
1
validate :school_presence_for_sub_admin
-
-
1
after_create :send_email
-
1
after_update :send_email
-
-
-
1
def send_email
-
160
AccountBlock::AdminUserMailer
-
.with(account: self)
-
.admin_permission_email.deliver
-
end
-
-
-
-
1
private
-
-
1
def school_presence_for_sub_admin
-
298
if sub_admin? && school_id.blank?
-
1
errors.add(:school_id, "must be present for sub admin")
-
297
elsif super_admin? && school_id.present?
-
1
errors.add(:school_id, "No need for super admin to have a school ID")
-
end
-
end
-
end
-
1
class ApplicationRecord < ActiveRecord::Base
-
1
self.abstract_class = true
-
end
-
1
module BuilderBase
-
1
class ApplicationRecord < ::ApplicationRecord
-
1
self.abstract_class = true
-
1
self.store_full_sti_class = false
-
end
-
end
-
module BxBlockAccountGroups
-
class AccountGroup < ApplicationRecord
-
self.table_name = "account_groups_account_groups"
-
-
belongs_to :account, class_name: "AccountBlock::Account"
-
belongs_to :group, class_name: "BxBlockAccountGroups::Group",
-
foreign_key: "account_groups_group_id"
-
end
-
end
-
1
module BxBlockAccountGroups
-
1
class ApplicationRecord < BuilderBase::ApplicationRecord
-
1
self.abstract_class = true
-
end
-
end
-
1
module BxBlockAccountGroups
-
1
class Group < BxBlockAccountGroups::ApplicationRecord
-
1
self.table_name = :account_groups_groups
-
1
before_save :process_settings
-
1
validates :name, presence: true
-
1
has_many :account_groups, foreign_key: "account_groups_group_id", dependent: :destroy
-
1
has_many :accounts, through: :account_groups
-
-
1
ROLE_ADMIN = "group_admin"
-
1
ROLE_BASIC = "group_basic"
-
-
1
def process_settings
-
self.settings = JSON.parse(settings) if settings.is_a? String
-
end
-
end
-
end
-
module BxBlockAddress
-
class Address < ApplicationRecord
-
self.table_name = :addresses
-
-
belongs_to :account, class_name: "AccountBlock::Account",
-
foreign_key: "addressble_id"
-
reverse_geocoded_by :latitude, :longitude
-
-
enum address_type: {"Home" => 0, "Work" => 1, "Other" => 2}
-
-
validates :address_type, presence: true
-
-
after_validation :reverse_geocode
-
-
before_create :add_address_type
-
-
private
-
-
def add_address_type
-
self.address_type = "Home" unless address_type.present?
-
end
-
end
-
end
-
module BxBlockAddress
-
class ApplicationRecord < BuilderBase::ApplicationRecord
-
self.abstract_class = true
-
end
-
end
-
module BxBlockAdmin
-
class ApplicationRecord < BuilderBase::ApplicationRecord
-
self.abstract_class = true
-
end
-
end
-
module BxBlockAnalytics7
-
class ApplicationRecord < BuilderBase::ApplicationRecord
-
self.abstract_class = true
-
end
-
end
-
module BxBlockAnnotations
-
class Annotation < BxBlockAnnotations::ApplicationRecord
-
self.table_name = :bx_block_annotations
-
-
belongs_to :account, class_name: 'AccountBlock::Account'
-
scope :ordered_by_id, -> { reorder(:id).reverse_order }
-
end
-
end
-
module BxBlockAnnotations
-
class ApplicationRecord < BuilderBase::ApplicationRecord
-
self.abstract_class = true
-
end
-
end
-
module BxBlockAppointmentManagement
-
class ApplicationRecord < BuilderBase::ApplicationRecord
-
self.abstract_class = true
-
end
-
end
-
module BxBlockAppointmentManagement
-
class Availability < ApplicationRecord
-
include Wisper::Publisher
-
self.table_name = :availabilities
-
-
belongs_to :service_provider,
-
class_name: "AccountBlock::Account", foreign_key: :service_provider_id
-
scope :sp_details, ->(sp_id, availability_date) {
-
find_by(service_provider_id: sp_id, availability_date: availability_date)
-
}
-
-
validates_presence_of :availability_date, :start_time, :end_time
-
# validate :check_date
-
validate :check_presence_of_days_slot, if: proc { |availability| availability.new_record? }
-
-
before_save :set_params
-
-
scope :todays_availabilities, -> {
-
where(availability_date: Date.today.strftime("%d/%m/%Y")).first
-
}
-
scope :filter_by_date, ->(date) {
-
where(availability_date: Date.parse(date).strftime("%d/%m/%Y"))
-
}
-
scope :available_service_provider, ->(date) {
-
where(
-
availability_date: Date.parse(date).strftime("%d/%m/%Y")
-
).order(:available_slots_count)&.first&.service_provider
-
}
-
after_create :create_time_slots, :update_slot_count
-
-
def todays_online_hours
-
# Date will be in hour
-
full_day_slot = ((Time.parse(end_time) - Time.parse(start_time)) / 3600)
-
if unavailable_end_time.present? && unavailable_start_time.present?
-
unavailable_slot = ((Time.parse(unavailable_end_time) -
-
Time.parse(unavailable_start_time)) / 3600)
-
end
-
unavailable_slot.present? ? full_day_slot - unavailable_slot : full_day_slot
-
end
-
-
def slots_list
-
already_booked_slots = get_booked_slots(Date.strptime(availability_date, "%d/%m/%Y"))
-
availability = self
-
unless availability.present?
-
return errors.add(
-
:availability, "Service provider is unavailable for today"
-
)
-
end
-
slots = BxBlockAppointmentManagement::TimeSlotsCalculator.new.calculate_time_slots(
-
availability.start_time, availability.end_time, 59
-
)
-
slots.each_with_index do |slot, index|
-
next if slot[:booked_status]
-
already_booked_slots.each do |booked_slot|
-
if (Time.parse(slot[:from])..Time.parse(slot[:to])).cover?(booked_slot[:start_time])
-
slot[:booked_status] = true
-
while slots[index + 1].present? && (booked_slot[:start_time]..booked_slot[:end_time]).cover?(Time.parse(slots[index + 1][:from]))
-
slots[index + 1][:booked_status] = true
-
index += 1
-
break unless slots[index + 1].present?
-
end
-
end
-
end
-
end
-
slots
-
end
-
-
def update_slot_count
-
available_slots_count = slots_list.to_a.count { |time| time[:booked_status] == false }
-
update(available_slots_count: available_slots_count)
-
end
-
-
private
-
-
def check_date
-
errors.add(:invalid_date, "Invalid Date, Please choose current date") unless
-
Date.parse(availability_date).today?
-
end
-
-
def get_booked_slots order_date
-
BookedSlot.where(
-
service_provider_id: service_provider,
-
booking_date: order_date
-
).map do |booked_slot|
-
{start_time: booked_slot.start_time.to_time, end_time: booked_slot.end_time.to_time}
-
end
-
end
-
-
def check_presence_of_days_slot
-
if service_provider.present?
-
slot = Availability.find_by(
-
service_provider_id: service_provider.id,
-
availability_date: Date.parse(availability_date).strftime("%d/%m/%Y")
-
)
-
end
-
errors.add(:slot_error, "You have already slot for the day") if slot.present?
-
end
-
-
def set_params
-
self.availability_date = Date.parse(availability_date).strftime("%d/%m/%Y")
-
self.start_time = Time.parse(start_time).strftime("%I:%M %p")
-
self.end_time = Time.parse(end_time).strftime("%I:%M %p")
-
if unavailable_start_time.present?
-
self.unavailable_start_time = Time.parse(unavailable_start_time).strftime("%I:%M %p")
-
end
-
if unavailable_end_time.present?
-
self.unavailable_end_time = Time.parse(unavailable_end_time).strftime("%I:%M %p")
-
end
-
end
-
-
def create_time_slots
-
new_time_slots = TimeSlotsCalculator.new.calculate_time_slots(
-
start_time, end_time, 59
-
)
-
update_column("timeslots", new_time_slots)
-
end
-
end
-
end
-
module BxBlockAppointmentManagement
-
class BookedSlot < ApplicationRecord
-
self.table_name = :bx_block_appointment_management_booked_slots
-
-
belongs_to :service_provider, class_name: "AccountBlock::Account"
-
end
-
end
-
module BxBlockAttachment
-
class ApplicationRecord < BuilderBase::ApplicationRecord
-
self.abstract_class = true
-
end
-
end
-
module BxBlockAttachment
-
class Attachment < BxBlockAttachment::ApplicationRecord
-
self.table_name = :attachments
-
include Wisper::Publisher
-
-
has_one_attached :attachment
-
belongs_to :account, class_name: 'AccountBlock::Account'
-
after_create :default_values
-
scope :not_expired, -> {where('is_expired = ?',false)}
-
-
def default_values
-
self.colour = "Greyscale"
-
self.layout = "Portrait"
-
self.page_size = "A4"
-
self.print_sides = "Both"
-
self.scale = "Print all pages"
-
self.print_pages_from = 1
-
self.print_pages_to = 1
-
self.total_pages = 1
-
end
-
-
def self.attachment_expire
-
attachments = BxBlockAttachment::Attachment.where(
-
"created_at + '4 hours'::interval < ? AND is_expired =?", DateTime.now, false
-
)
-
if attachments.present?
-
attachments.each do |attachment|
-
broadcast(:attachment_expired, attachment)
-
attachment.update_attributes(:is_expired => true)
-
if attachment.attachment.attached?
-
attachment.attachment.purge
-
attachment.destroy
-
end
-
end
-
end
-
-
expired_attachments = BxBlockAttachment::Attachment.where(
-
"created_at + '4 hours'::interval < ? AND is_expired =?", DateTime.now, true
-
)
-
if expired_attachments.present?
-
expired_attachments.each do |at|
-
at.destroy
-
end
-
end
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
module BxBlockAttachment
-
class FileAttachment < BxBlockAttachment::ApplicationRecord
-
self.table_name = :bx_block_attachment_file_attachments
-
include Wisper::Publisher
-
has_one_attached :attachment
-
enum content_type: %i[doc jpg pdf mp3 mp4]
-
validates :content_type, presence: true
-
validates :attachment, presence: true
-
validate :attachment_size
-
-
private
-
def attachment_size
-
return unless attachment.attached?
-
if attachment.blob.byte_size > MAXATTACHMENTSIZE.megabytes
-
errors.add(:attachment, "size needs to be less than #{MAXATTACHMENTSIZE} MB")
-
end
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
1
module BxBlockBulkUploading
-
1
class ApplicationRecord < BuilderBase::ApplicationRecord
-
1
self.abstract_class = true
-
end
-
end
-
# frozen_string_literal: true
-
-
module BxBlockBulkUploading
-
class Attachment < BxBlockBulkUploading::ApplicationRecord
-
self.table_name = :attachments
-
include Wisper::Publisher
-
-
OPTIONS = %i[processing completed failed].freeze
-
enum status: OPTIONS
-
-
has_many_attached :files
-
belongs_to :account, class_name: "AccountBlock::Account"
-
-
validates :files, limit: {max: 100},
-
size: {less_than: 5.megabytes, message: "Size of individual file should be less than 5 MB"}
-
end
-
end
-
# frozen_string_literal: true
-
# require 'pdf/reader'
-
-
1
module BxBlockBulkUploading
-
1
class BundleManagement < BxBlockBulkUploading::ApplicationRecord
-
1
self.table_name = :bx_block_bulk_uploading_bundles
-
-
1
has_many_attached :cover_images
-
1
has_and_belongs_to_many :ebooks,
-
join_table: 'bundles_ebooks',
-
class_name: 'BxBlockBulkUploading::Ebook',
-
foreign_key: 'bx_block_bulk_uploading_bundle_id',
-
association_foreign_key: 'bx_block_bulk_uploading_ebook_id'
-
-
1
validates :title, presence: true, length: { in: 1..100 }
-
1
validates :description, presence: true, length: { in: 1..300 }
-
1
validates :total_pricing, presence: true
-
1
validates :board, presence: true
-
1
validates :school_class_id, presence: true
-
1
validates :cover_images, attached: true, content_type: ['image/png', 'image/jpg', 'image/jpeg']
-
1
validate :validate_max_images
-
1
validate :at_least_one_ebook
-
-
1
def calculate_revised_price
-
3
selected_ebook_prices = self.ebooks.map(&:price)
-
3
self.total_pricing = selected_ebook_prices.sum
-
end
-
-
1
private
-
-
1
def validate_max_images
-
29
return unless cover_images.attached? && cover_images.length > 3
-
-
errors.add(:cover_images, 'cannot have more than 3 attached cover_images')
-
end
-
-
1
def at_least_one_ebook
-
29
errors.add(:base, 'Select at least one ebook to create bundle!') if ebook_ids.blank?
-
end
-
end
-
end
-
# frozen_string_literal: true
-
1
require 'pdf/reader'
-
1
require 'searchkick'
-
1
module BxBlockBulkUploading
-
1
class Ebook < BxBlockBulkUploading::ApplicationRecord
-
1
self.table_name = :bx_block_bulk_uploading_ebooks
-
1
include Searchkick
-
-
1
has_one_attached :excel_file
-
1
has_one_attached :pdf
-
1
has_many_attached :images
-
1
has_many :ebook_allotments, class_name: "BxBlockBulkUploading::EbookAllotment"
-
1
has_many :accounts, class_name: "AccountBlock::Account", through: :ebook_allotments
-
-
1
has_many :remove_books, class_name: 'RemoveBook', foreign_key: 'ebook_id'
-
1
has_many :remove_students, through: :remove_books, source: :account
-
-
1
before_save :publication_date_cannot_be_in_the_future
-
1
validates :pdf, attached: true, content_type: ['application/pdf']
-
1
validates :images, attached: true, content_type: ['image/png', 'image/jpg', 'image/jpeg']
-
1
validates :title, presence: true, uniqueness: true, length: { maximum: 100 }
-
1
validates :author, presence: true, length: { maximum: 100 }
-
1
validates :edition, presence: true, length: { maximum: 100 }
-
1
validates :description, presence: true, length: { maximum: 300 }
-
1
validates :publisher, presence: true
-
1
validates :board, presence: true
-
1
validates :subject, presence: true
-
1
validates :school_class_id, presence: true
-
1
validates :language, length: { maximum: 70 }
-
1
validates :price, presence: true #, numericality: { greater_than: 0 }
-
1
validate :valid_date_format
-
1
validates_format_of :commission_percentage, with: /\A\d+(\.\d+)?%?\z/, message: 'should be a valid percentage'
-
1
validate :validate_max_images
-
-
-
1
def pdf_url
-
pdf.attached? ? Rails.application.routes.url_helpers.rails_blob_path(pdf, only_path: true) : nil
-
end
-
-
# def search_data
-
# {
-
# title: title,
-
# author: author,
-
# publisher: publisher,
-
# subject: subject
-
# }
-
# end
-
-
1
private
-
-
1
def valid_date_format
-
159
if publication_date.present? && !publication_date.to_s.match(/\A\d{4}-\d{2}-\d{2}\z/)
-
errors.add(:publication_date, "has an invalid date format. Please use YYYY-MM-DD format.")
-
end
-
end
-
-
1
def validate_max_images
-
159
return unless images.attached? && images.length > 3
-
-
errors.add(:images, 'cannot have more than 3 attached images')
-
end
-
-
1
def publication_date_cannot_be_in_the_future
-
115
errors.add(:publication_date, "Future date is not allow to select.") if publication_date.present? && publication_date > Date.today
-
end
-
end
-
end
-
-
1
module BxBlockBulkUploading
-
1
class EbookAllotment < BxBlockBulkUploading::ApplicationRecord
-
1
self.table_name = :ebook_allotments
-
1
belongs_to :account, class_name: "AccountBlock::Account"
-
1
belongs_to :ebook, class_name: "BxBlockBulkUploading::Ebook"
-
1
belongs_to :student, class_name: "AccountBlock::Account", foreign_key: "student_id"
-
end
-
end
-
-
1
module BxBlockBulkUploading
-
1
class RemoveBook < BxBlockBulkUploading::ApplicationRecord
-
1
self.table_name = :remove_books
-
1
belongs_to :account, class_name: 'AccountBlock::Account'
-
1
belongs_to :ebook, class_name: 'BxBlockBulkUploading::Ebook'
-
end
-
end
-
1
module BxBlockCatalogue
-
1
class ApplicationRecord < BuilderBase::ApplicationRecord
-
1
self.abstract_class = true
-
end
-
end
-
1
require 'searchkick'
-
1
module BxBlockCatalogue
-
1
class Assignment < BxBlockCatalogue::ApplicationRecord
-
1
self.table_name = :assignments
-
1
include Searchkick
-
-
1
has_one_attached :assignment
-
1
belongs_to :subject_management, class_name: "BxBlockCatalogue::SubjectManagement", optional: true
-
1
validates_presence_of :title, :description, :assignment
-
-
1
validate :assignment_file_format
-
-
1
private
-
-
1
def assignment_file_format
-
70
return unless assignment.attached?
-
-
66
unless assignment.blob.content_type.in?(%w[application/pdf application/msword application/vnd.openxmlformats-officedocument.wordprocessingml.document])
-
2
errors.add(:assignment, 'must be a PDF or DOC file')
-
end
-
end
-
end
-
end
-
module BxBlockCatalogue
-
class Brand < BxBlockCatalogue::ApplicationRecord
-
self.table_name = :brands
-
-
enum currency: %i(GBP INR USD EUR)
-
validates :name, presence: true, uniqueness: { case_sensitive: false }
-
validates :currency, inclusion: { in: currencies.keys }
-
end
-
end
-
1
module BxBlockCatalogue
-
1
class Catalogue < BxBlockCatalogue::ApplicationRecord
-
1
ActiveSupport.run_load_hooks(:catalogue, self)
-
1
PAGE = 1
-
1
PER_PAGE = 10
-
-
1
self.table_name = :catalogues
-
-
1
enum availability: %i[in_stock out_of_stock]
-
-
1
belongs_to :category,
-
class_name: "BxBlockCategories::Category",
-
foreign_key: "category_id"
-
-
1
belongs_to :sub_category,
-
class_name: "BxBlockCategories::SubCategory",
-
foreign_key: "sub_category_id"
-
-
1
belongs_to :brand, optional: true
-
-
1
has_many :reviews, dependent: :destroy
-
1
has_many :catalogue_variants, dependent: :destroy
-
1
has_and_belongs_to_many :tags, join_table: :catalogues_tags,
-
association_foreign_key: "catalogue_tag_id", foreign_key: :catalogue_id
-
-
1
has_many_attached :images, dependent: :destroy
-
-
1
accepts_nested_attributes_for :catalogue_variants, allow_destroy: true
-
-
1
def average_rating
-
return 0 if reviews.size.zero?
-
-
total_rating = 0
-
reviews.each do |r|
-
total_rating += r.rating
-
end
-
total_rating.to_f / reviews.size.to_f
-
end
-
end
-
end
-
module BxBlockCatalogue
-
class CatalogueVariant < BxBlockCatalogue::ApplicationRecord
-
self.table_name = :catalogue_variants
-
-
belongs_to :catalogue
-
belongs_to :catalogue_variant_color, optional: true
-
belongs_to :catalogue_variant_size, optional: true
-
-
has_many_attached :images, dependent: :destroy
-
end
-
end
-
module BxBlockCatalogue
-
class CatalogueVariantColor < BxBlockCatalogue::ApplicationRecord
-
self.table_name = :catalogue_variant_colors
-
validates :name, presence: true
-
end
-
end
-
module BxBlockCatalogue
-
class CatalogueVariantSize < BxBlockCatalogue::ApplicationRecord
-
self.table_name = :catalogue_variant_sizes
-
validates :name, presence: true
-
end
-
end
-
module BxBlockCatalogue
-
class CataloguesTag < BxBlockCatalogue::ApplicationRecord
-
self.table_name = :catalogues_tags
-
-
belongs_to :catalogue
-
belongs_to :tag, foreign_key: "catalogue_tag_id"
-
end
-
end
-
module BxBlockCatalogue
-
class Review < BxBlockCatalogue::ApplicationRecord
-
self.table_name = :catalogue_reviews
-
-
belongs_to :catalogue
-
end
-
end
-
1
module BxBlockCatalogue
-
1
class Subject < BxBlockCatalogue::ApplicationRecord
-
1
self.table_name = :subjects
-
1
belongs_to :class_division, class_name: "BxBlockCategories::ClassDivision",:foreign_key => "class_division_id", optional: true
-
1
belongs_to :account, class_name: "AccountBlock::Account", optional: true
-
1
has_many :subject_managements, class_name: "BxBlockCatalogue::SubjectManagement", dependent: :destroy
-
1
validates :subject_name, uniqueness: true, presence: true
-
end
-
end
-
1
module BxBlockCatalogue
-
1
class SubjectManagement < BxBlockCatalogue::ApplicationRecord
-
1
self.table_name = :subject_managements
-
1
belongs_to :class_division, class_name: "BxBlockCategories::ClassDivision",:foreign_key => "class_division_id", optional: true
-
1
belongs_to :account, class_name: "AccountBlock::Account", optional: true
-
1
belongs_to :subject, class_name: "BxBlockCatalogue::Subject", :foreign_key => "subject_id"
-
1
has_many :videos_lectures, class_name: "BxBlockCatalogue::VideosLecture", dependent: :destroy
-
1
has_many :assignments, class_name: "BxBlockCatalogue::Assignment", dependent: :destroy
-
end
-
end
-
module BxBlockCatalogue
-
class Tag < BxBlockCatalogue::ApplicationRecord
-
self.table_name = :catalogue_tags
-
validates :name, presence: true, uniqueness: { case_sensitive: false }
-
has_and_belongs_to_many :catalogues, join_table: :catalogues_tags,
-
association_foreign_key: :catalogue_id, foreign_key: :catalogue_tag_id
-
end
-
end
-
1
module BxBlockCatalogue
-
1
class VideosLecture < BxBlockCatalogue::ApplicationRecord
-
1
self.table_name = :videos_uploads
-
1
belongs_to :subject_management, class_name: "BxBlockCatalogue::SubjectManagement", optional: true
-
1
validates_presence_of :title, :description, :video
-
1
validate :validate_video_link
-
-
1
private
-
-
1
def validate_video_link
-
55
uri = URI.parse(video)
-
53
errors.add(:video, "must be a valid URL") unless uri.is_a?(URI::HTTP) || uri.is_a?(URI::HTTPS)
-
rescue URI::InvalidURIError
-
2
errors.add(:video, "must be a valid URL")
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
1
module BxBlockCategories
-
1
class ApplicationRecord < BuilderBase::ApplicationRecord
-
1
self.abstract_class = true
-
end
-
end
-
# frozen_string_literal: true
-
-
module BxBlockCategories
-
class Category < BxBlockCategories::ApplicationRecord
-
include ActiveStorageSupport::SupportForBase64
-
self.table_name = :categories
-
-
has_one_base64_attached :light_icon
-
has_one_base64_attached :light_icon_active
-
has_one_base64_attached :light_icon_inactive
-
has_one_base64_attached :dark_icon
-
has_one_base64_attached :dark_icon_active
-
has_one_base64_attached :dark_icon_inactive
-
-
has_and_belongs_to_many :sub_categories,
-
join_table: :categories_sub_categories, dependent: :destroy
-
-
has_many :contents, class_name: "BxBlockContentmanagement::Content", dependent: :destroy
-
has_many :ctas, class_name: "BxBlockCategories::Cta", dependent: :nullify
-
-
has_many :user_categories, class_name: "BxBlockCategories::UserCategory",
-
join_table: "user_categoeries", dependent: :destroy
-
has_many :accounts, class_name: "AccountBlock::Account", through: :user_categories,
-
join_table: "user_categoeries"
-
-
validates :name, uniqueness: true, presence: true
-
validates_uniqueness_of :identifier, allow_blank: true
-
-
enum identifier: %w[k12 higher_education govt_job competitive_exams upskilling]
-
end
-
end
-
1
module BxBlockCategories
-
1
class ClassDivision < ApplicationRecord
-
1
self.table_name = :class_divisions
-
1
belongs_to :school_class, class_name: "BxBlockCategories::SchoolClass", optional: true
-
1
has_many :accounts, class_name: "AccountBlock::Account", dependent: :destroy
-
1
has_many :subjects, class_name: "BxBlockCatalogue::Subject"
-
1
has_many :subject_managements, class_name: "BxBlockCatalogue::SubjectManagement", dependent: :destroy
-
1
validates :division_name, presence: true
-
1
validates :account_id, presence: true, uniqueness: true
-
end
-
end
-
# frozen_string_literal: true
-
-
module BxBlockCategories
-
class Cta < ApplicationRecord
-
self.table_name = :cta
-
-
belongs_to :category
-
-
mount_uploader :long_background_image, ImageUploader
-
mount_uploader :square_background_image, ImageUploader
-
-
enum text_alignment: %w[centre left right]
-
enum button_alignment: %w[centre left right], _suffix: true
-
-
validates :headline, :text_alignment, presence: true, if: -> { is_text_cta }
-
validates :button_text, :redirect_url, :button_alignment, presence: true,
-
if: -> { has_button }
-
-
def name
-
headline
-
end
-
end
-
end
-
1
module BxBlockCategories
-
1
class School < ApplicationRecord
-
1
self.table_name = :schools
-
1
EMAIL_REGEX = /\w+@\w+.{1}[a-zA-Z]{2,}/
-
-
1
has_many :accounts, class_name: "AccountBlock::Account", foreign_key: "school_id", dependent: :destroy
-
1
has_many :school_classes, class_name: "BxBlockCategories::SchoolClass", dependent: :destroy
-
-
1
validates_presence_of :name, :email, :board, :phone_number, :principal_name
-
1
validates_format_of :email, with: EMAIL_REGEX
-
1
validates_uniqueness_of :email, :name
-
1
validates_length_of :phone_number, is: 10, numericality: { only_integer: true }
-
-
1
before_destroy :delete_accounts
-
-
# before_validation :valid_phone_number
-
# has_many :departments, class_name: "BxBlockCategories::Department", dependent: :destroy
-
# has_many :class_divisions, class_name: "BxBlockCategories::ClassDivision", dependent: :destroy
-
-
1
private
-
-
1
def delete_accounts
-
1
self.accounts.each do |account|
-
account.delete
-
end
-
end
-
-
1
def valid_phone_number
-
unless Phonelib.valid?(phone_number)
-
errors.add(:phone_number, "Invalid or Unrecognized Phone Number")
-
end
-
end
-
end
-
end
-
1
module BxBlockCategories
-
1
class SchoolClass < ApplicationRecord
-
1
self.table_name = :school_classes
-
1
belongs_to :school, class_name: "BxBlockCategories::School"
-
1
has_many :class_divisions, class_name: "BxBlockCategories::ClassDivision", dependent: :destroy
-
1
accepts_nested_attributes_for :class_divisions, allow_destroy: true, reject_if: :all_blank
-
1
validates_associated :class_divisions
-
1
validates :class_number,presence: true, uniqueness: { scope: :school_id, message: "Class with this number already exists in the school." }
-
1
validate :at_least_one_class_division
-
-
1
private
-
1
def at_least_one_class_division
-
166
errors.add(:base, 'At least one class division is required.') unless class_divisions.any?
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
module BxBlockCategories
-
class SubCategory < BxBlockCategories::ApplicationRecord
-
self.table_name = :sub_categories
-
-
has_and_belongs_to_many :categories, join_table: :categories_sub_categories, dependent: :destroy
-
belongs_to :parent, class_name: "BxBlockCategories::SubCategory", optional: true
-
has_many :sub_categories, class_name: "BxBlockCategories::SubCategory",
-
foreign_key: :parent_id, dependent: :destroy
-
has_many :user_sub_categories, class_name: "BxBlockCategories::UserSubCategory",
-
join_table: "user_sub_categoeries", dependent: :destroy
-
has_many :accounts, class_name: "AccountBlock::Account", through: :user_sub_categories,
-
join_table: "user_sub_categoeries"
-
-
validates :name, uniqueness: true, presence: true
-
validate :check_parent_categories
-
-
private
-
-
def check_parent_categories
-
errors.add(:base, "Please select categories or a parent.") if categories.blank? && parent.blank?
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
module BxBlockCategories
-
class UserCategory < ApplicationRecord
-
self.table_name = :user_categories
-
-
belongs_to :account, class_name: "AccountBlock::Account"
-
belongs_to :category
-
end
-
end
-
# frozen_string_literal: true
-
-
module BxBlockCategories
-
class UserSubCategory < ApplicationRecord
-
self.table_name = :user_sub_categories
-
-
belongs_to :account, class_name: "AccountBlock::Account"
-
belongs_to :sub_category
-
end
-
end
-
module BxBlockCfhighlightingandunderliningtext
-
class ApplicationRecord < BuilderBase::ApplicationRecord
-
self.abstract_class = true
-
end
-
end
-
# frozen_string_literal: true
-
-
module BxBlockComments
-
class ApplicationRecord < BuilderBase::ApplicationRecord
-
self.abstract_class = true
-
end
-
end
-
# frozen_string_literal: true
-
-
module BxBlockComments
-
class Comment < BxBlockComments::ApplicationRecord
-
self.table_name = :comments
-
if ENV['TEMPLATEAPP_DATABASE']
-
include PublicActivity::Model
-
tracked owner: proc { |controller, _model| controller&.current_user }
-
end
-
-
validates :comment, presence: true
-
-
belongs_to :account, class_name: "AccountBlock::Account"
-
belongs_to :commentable, polymorphic: true
-
-
def self.policy_class
-
::BxBlockComments::CommentPolicy
-
end
-
end
-
end
-
1
module BxBlockContactUs
-
1
class ApplicationRecord < BuilderBase::ApplicationRecord
-
1
self.abstract_class = true
-
end
-
end
-
1
module BxBlockContactUs
-
1
class Contact < BxBlockContactUs::ApplicationRecord
-
1
self.table_name = :contacts
-
-
1
EMAIL_REGEX = /\w+@\w+.{1}[a-zA-Z]{2,}/
-
-
1
belongs_to :account, class_name: "AccountBlock::Account", optional: true
-
-
# validates :name, presence: true
-
-
# validate :valid_email, if: Proc.new { |c| c.email.present? }
-
# validate :valid_phone_number, if: Proc.new { |c| c.phone_number.present? }
-
-
1
def self.filter(query_params)
-
ContactFilter.new(self, query_params).call
-
end
-
-
1
private
-
-
1
def valid_email
-
validator = AccountBlock::EmailValidation.new(email)
-
errors.add(:email, "invalid") if !validator.valid?
-
end
-
-
1
def valid_phone_number
-
validator = AccountBlock::PhoneValidation.new(phone_number)
-
errors.add(:phone_number, "invalid") if !validator.valid?
-
end
-
end
-
end
-
1
module BxBlockContentManagement
-
1
class AboutUs < ApplicationRecord
-
1
self.table_name = :about_us
-
1
EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
-
1
PHONE_NUMBER_REGEX = /\A\d{10}\z/
-
#PHONE_NUMBER_REGEX = /\A\+\d{1,3}\s\d+\z/
-
# Validations
-
1
validate :only_one_entry_allowed
-
1
validates :title, :email, :phone_number, presence: true
-
1
validates :email, format: { with: EMAIL_REGEX }
-
1
validates :phone_number, presence: true, format: { with: PHONE_NUMBER_REGEX }
-
-
1
def only_one_entry_allowed
-
20
if AboutUs.exists? && !self.persisted?
-
17
errors.add(:base, 'Only one entry is allowed, please delete the existing one to create a new entry.')
-
end
-
end
-
end
-
end
-
1
module BxBlockContentManagement
-
1
class ApplicationRecord < BuilderBase::ApplicationRecord
-
1
self.abstract_class = true
-
end
-
end
-
module BxBlockContentManagement
-
class Audio < ApplicationRecord
-
self.table_name = :audios
-
mount_uploader :audio, AudioUploader
-
-
# Associations
-
belongs_to :attached_item, polymorphic: true
-
-
# Validations
-
validates_presence_of :audio
-
end
-
end
-
module BxBlockContentManagement
-
class AudioPodcast < ApplicationRecord
-
include Contentable
-
-
self.table_name = :audio_podcasts
-
-
validates_presence_of :heading
-
-
has_one :image, as: :attached_item, dependent: :destroy
-
has_one :audio, as: :attached_item, dependent: :destroy
-
-
accepts_nested_attributes_for :image, allow_destroy: true
-
accepts_nested_attributes_for :audio, allow_destroy: true
-
-
def name
-
heading
-
end
-
-
def image_url
-
image.image_url if image.present?
-
end
-
-
def video_url
-
nil
-
end
-
-
def audio_url
-
audio.audio_url if audio.present?
-
end
-
-
def study_material_url
-
nil
-
end
-
end
-
-
end
-
module BxBlockContentManagement
-
class Author < ApplicationRecord
-
self.table_name = :authors
-
has_many :contents, class_name: "BxBlockContentManagement::Content", dependent: :destroy
-
validates :name, :bio, presence: true
-
validates :bio, :length => {
-
:maximum => 500, :too_long => "should not greater then %{count} words"
-
}
-
has_one :image, as: :attached_item, dependent: :destroy
-
-
accepts_nested_attributes_for :image, allow_destroy: true
-
end
-
end
-
module BxBlockContentManagement
-
class Bookmark < ApplicationRecord
-
self.table_name = :bookmarks
-
belongs_to :account, class_name: "AccountBlock::Account"
-
belongs_to :content, class_name: "BxBlockContentManagement::Content"
-
validates_presence_of :account_id, :content_id
-
validates :account_id, uniqueness: { scope: :content_id, message: "content with this account is already taken"}
-
end
-
end
-
module BxBlockContentManagement
-
class Content < ApplicationRecord
-
self.table_name = :contents
-
-
MAX_TAG_CHARACTERS = 35
-
-
belongs_to :category, class_name: 'BxBlockCategories::Category', foreign_key: 'category_id'
-
belongs_to :sub_category, class_name: 'BxBlockCategories::SubCategory', foreign_key: 'sub_category_id'
-
belongs_to :content_type, class_name: 'BxBlockContentManagement::ContentType', foreign_key: 'content_type_id'
-
belongs_to :language, class_name: 'BxBlockLanguageOptions::Language', foreign_key: 'language_id'
-
belongs_to :contentable, polymorphic: true, inverse_of: :contentable, autosave: true, dependent: :destroy
-
belongs_to :author, class_name: 'BxBlockContentManagement::Author', optional: true
-
has_many :bookmarks, class_name: "BxBlockContentManagement::Bookmark", dependent: :destroy
-
has_many :account_bookmarks, class_name: "AccountBlock::Account", through: :bookmarks, source: :account
-
-
validates :author_id, presence: true, if: -> { self.content_type&.blog? }
-
validates :publish_date, presence: true, if: ->{ self.publish? }
-
validates :status, presence: true
-
validate :validate_publish_date, on: :update
-
validate :validate_status, on: :update
-
validate :validate_content_type, on: :update
-
validate :validate_approve_status, on: :update
-
validate :max_tag_char_length
-
validates :feedback, presence: true, if: -> { self.rejected? }
-
-
scope :operations_l1_content, -> { where(review_status: ["pending", "rejected", "submit_for_review"]) }
-
scope :submit_for_review_l1_content, -> { where(review_status: ["submit_for_review"]) }
-
-
attr_accessor :current_user_id
-
-
-
after_initialize :set_defaults
-
-
accepts_nested_attributes_for :contentable
-
-
scope :non_archived, -> { where(archived: false) }
-
scope :archived, -> { where(archived: true) }
-
-
searchkick
-
-
acts_as_taggable_on :tags
-
-
enum status: ["draft", "publish", "disable"]
-
-
enum review_status: ["pending", "submit_for_review", "approve", "rejected"]
-
-
scope :published, -> {publish.where("publish_date < ?", DateTime.current)}
-
scope :blogs_content, -> { joins(:content_type).where(content_types: {identifier: 'blog'}) }
-
scope :filter_content, ->(categories, sub_categories, content_types) {
-
where(category: categories, sub_category: sub_categories, content_type: content_types)
-
}
-
scope :in_review, -> { where(review_status: "submit_for_review")}
-
-
def contentable_attributes=(attributes)
-
self.contentable_type = content_type&.type_class
-
if self.contentable_type
-
some_contentable = self.contentable_type.constantize.find_or_initialize_by(id: self.contentable_id)
-
some_contentable.attributes = attributes
-
self.contentable = some_contentable
-
end
-
end
-
-
def name
-
contentable&.name
-
end
-
-
def description
-
contentable&.description
-
end
-
-
def image
-
contentable&.image_url
-
end
-
-
def video
-
contentable&.video_url
-
end
-
-
def audio
-
contentable&.audio_url
-
end
-
-
def study_material
-
contentable&.study_material_url
-
end
-
-
def search_data
-
attributes.merge(
-
category_name: self.category.name,
-
sub_category_name: self.sub_category.name,
-
language_name: self.language.name,
-
content_type_name: self.content_type.name,
-
contentable: self.contentable,
-
tags: self.tags.map(&:name).join(" ")
-
)
-
end
-
-
private
-
-
def max_tag_char_length
-
self.tag_list.each do |tag|
-
if tag.length > MAX_TAG_CHARACTERS
-
errors[:tag] << "#{tag} must be shorter than #{MAX_TAG_CHARACTERS} characters maximum"
-
end
-
end
-
end
-
-
def validate_status
-
if self.draft? && will_save_change_to_status?
-
errors.add(:status, "can't be change to draft.")
-
end
-
end
-
-
def validate_content_type
-
errors.add(:content_type_id, "can't be updated") if will_save_change_to_content_type_id?
-
end
-
-
def validate_publish_date
-
if status_in_database == 'publish' && will_save_change_to_publish_date? && publish_date_in_database.present? &&
-
publish_date_in_database <= DateTime.current
-
errors.add(:publish_date, "can't be changed after published.")
-
end
-
end
-
-
def set_defaults
-
self.status ||= "draft"
-
end
-
-
def validate_approve_status
-
if will_save_change_to_status? && self.publish? && !self.approve?
-
errors.add(:status, "can't be published if content was not approved.")
-
end
-
end
-
end
-
end
-
module BxBlockContentManagement
-
class ContentText < ApplicationRecord
-
include Contentable
-
-
self.table_name = :content_texts
-
-
validates_presence_of :headline, :content
-
-
has_many :images, as: :attached_item, dependent: :destroy
-
has_many :videos, as: :attached_item, dependent: :destroy, class_name: 'BxBlockContentManagement::Video'
-
accepts_nested_attributes_for :videos, allow_destroy: true
-
accepts_nested_attributes_for :images, allow_destroy: true
-
-
def name
-
headline
-
end
-
-
def description
-
content
-
end
-
-
def image_url
-
images.first.image_url if images.present?
-
end
-
-
def video_url
-
videos.first.video_url if videos.present?
-
end
-
-
def audio_url
-
nil
-
end
-
-
def study_material_url
-
nil
-
end
-
end
-
end
-
module BxBlockContentManagement
-
class ContentType < ApplicationRecord
-
self.inheritance_column = nil
-
self.table_name = :content_types
-
-
TYPE_MAPPINGS = {
-
"Text" => BxBlockContentManagement::ContentText.name,
-
"Videos" => BxBlockContentManagement::ContentVideo.name,
-
"Live Stream" => BxBlockContentManagement::LiveStream.name,
-
"AudioPodcast" => BxBlockContentManagement::AudioPodcast.name,
-
"Test" => BxBlockContentManagement::Test.name,
-
"Epub" => BxBlockContentManagement::Epub.name
-
}.freeze
-
-
validates_presence_of :name, :type
-
validates_uniqueness_of :name, case_sensitive: false
-
validates_uniqueness_of :identifier, allow_blank: true
-
-
has_many :contents, class_name: "BxBlockContentManagement::Content", dependent: :destroy
-
has_and_belongs_to_many :partners, class_name: 'BxBlockRolesPermissions::Partner',
-
join_table: :content_types_partners, dependent: :destroy
-
-
-
enum type: ["Text", "Videos", "Live Stream", "AudioPodcast", "Test", "Epub"]
-
-
enum identifier: ["news_article", "audio_podcast", "blog", "live_streaming", "quiz", "assessment",
-
"study_material", "video_short", "video_full"]
-
-
def type_class
-
TYPE_MAPPINGS[type]
-
end
-
end
-
end
-
module BxBlockContentManagement
-
class ContentVideo < ApplicationRecord
-
include Contentable
-
-
self.table_name = :content_videos
-
-
validates_presence_of :headline
-
-
has_one :video, as: :attached_item, dependent: :destroy, class_name: 'BxBlockContentManagement::Video'
-
has_one :image, as: :attached_item, dependent: :destroy
-
accepts_nested_attributes_for :video, allow_destroy: true
-
accepts_nested_attributes_for :image, allow_destroy: true
-
-
def name
-
headline
-
end
-
-
def image_url
-
image.image_url if image.present?
-
end
-
-
def video_url
-
video.video_url if video.present?
-
end
-
-
def audio_url
-
nil
-
end
-
-
def study_material_url
-
nil
-
end
-
-
private
-
-
def validate_video_short_length
-
if self.video.present? and self.video.video.present?
-
errors.add(:video, "can't be more than 30 seconds") if get_time_duration(self.video.video) >= 30
-
end
-
end
-
-
def validate_video_full_length
-
if self.video.present? and self.video.video.present?
-
errors.add(:video, "can't be less than 30 seconds") if get_time_duration(self.video.video) < 30
-
end
-
end
-
-
def get_time_duration(video)
-
movie = FFMPEG::Movie.new(video.current_path)
-
movie.duration
-
end
-
end
-
end
-
module BxBlockContentManagement
-
class Epub < ApplicationRecord
-
include Contentable
-
-
self.table_name = :epubs
-
-
validates_presence_of :heading, :description
-
-
has_many :pdfs, class_name: 'BxBlockContentManagement::Pdf', as: :attached_item, dependent: :destroy
-
accepts_nested_attributes_for :pdfs, allow_destroy: true
-
-
def name
-
heading
-
end
-
-
def image_url
-
nil
-
end
-
-
def video_url
-
nil
-
end
-
-
def audio_url
-
nil
-
end
-
-
def study_material_url
-
pdfs.first.pdf_url if pdfs.present?
-
end
-
end
-
end
-
module BxBlockContentManagement
-
class Exam < ApplicationRecord
-
self.table_name = :exams
-
-
validates_presence_of :heading, :to, :from
-
-
validate :check_to_and_from
-
-
def name
-
heading
-
end
-
-
private
-
-
def check_to_and_from
-
if self.to.present? && self.from.present? && self.to < self.from
-
errors.add(:from, "can't be greater than to")
-
end
-
end
-
end
-
end
-
1
module BxBlockContentManagement
-
1
class FaqQuestion < ApplicationRecord
-
1
self.table_name = :faq_questions
-
# Validations
-
1
validates :question, :answer, presence: true
-
end
-
end
-
module BxBlockContentManagement
-
class Follow < ApplicationRecord
-
self.table_name = :follows
-
belongs_to :account, class_name: "AccountBlock::Account"
-
validates :account_id, uniqueness: { scope: :content_provider_id,
-
message: "content provider with this account is already taken"}
-
end
-
end
-
module BxBlockContentManagement
-
class Image < ApplicationRecord
-
self.table_name = :images
-
mount_uploader :image, ImageUploader
-
-
# Associations
-
belongs_to :attached_item, polymorphic: true
-
-
# Validations
-
validates_presence_of :image
-
end
-
end
-
module BxBlockContentManagement
-
class LiveStream < ApplicationRecord
-
include Contentable
-
-
self.table_name = :live_streams
-
-
validates_presence_of :headline
-
-
def name
-
headline
-
end
-
-
def image_url
-
nil
-
end
-
-
def video_url
-
nil
-
end
-
-
def audio_url
-
nil
-
end
-
-
def study_material_url
-
nil
-
end
-
end
-
end
-
module BxBlockContentManagement
-
class Pdf < ApplicationRecord
-
self.table_name = :pdfs
-
mount_uploader :pdf, PdfUploader
-
-
# Associations
-
belongs_to :attached_item, polymorphic: true
-
-
# Validations
-
validates_presence_of :pdf
-
end
-
end
-
module BxBlockContentManagement
-
class Test < ApplicationRecord
-
include Contentable
-
-
self.table_name = :tests
-
-
validates_presence_of :headline, :description
-
-
def name
-
headline
-
end
-
-
def image_url
-
nil
-
end
-
-
def video_url
-
nil
-
end
-
-
def audio_url
-
nil
-
end
-
-
def study_material_url
-
nil
-
end
-
-
-
end
-
end
-
module BxBlockContentManagement
-
class Video < ApplicationRecord
-
self.table_name = :content_management_videos
-
mount_uploader :video, VideoUploader
-
-
# Associations
-
belongs_to :attached_item, polymorphic: true
-
-
# Validations
-
validates_presence_of :video
-
end
-
end
-
module BxBlockCors
-
class ApplicationRecord < BuilderBase::ApplicationRecord
-
self.abstract_class = true
-
end
-
end
-
1
module BxBlockCouponCg
-
1
class ApplicationRecord < BuilderBase::ApplicationRecord
-
1
self.abstract_class = true
-
end
-
end
-
1
module BxBlockCouponCg
-
1
class CouponCode < BxBlockCouponCg::ApplicationRecord
-
1
self.table_name = :coupon_codes
-
-
DISCOUNT_TYPE = {
-
1
flat: 'flat',
-
percentage: 'percentage'
-
}.freeze
-
-
1
MAX_CART_VALUE = 100_000
-
1
MAX_DISCOUNT_VALUE = 100_000
-
-
1
validates :title, length: { maximum: 50 }, presence: true
-
1
validates :description, length: { maximum: 200 }
-
1
validates :code, length: { maximum: 50 }, presence: true
-
1
validates :code, uniqueness: true
-
-
1
validates :discount_type, acceptance: {
-
accept: [DISCOUNT_TYPE[:flat], DISCOUNT_TYPE[:percentage]]
-
}
-
1
validate :min_cart_value_not_negative
-
1
validate :max_cart_value_less_max_value
-
1
validate :discount_value
-
-
1
def min_cart_value_not_negative
-
if min_cart_value.negative?
-
errors.add(:min_cart_value, "Can't be less than zero")
-
end
-
end
-
-
1
def max_cart_value_less_max_value
-
if max_cart_value > MAX_CART_VALUE
-
errors.add(:max_cart_value, "Can't be more than #{MAX_CART_VALUE}")
-
end
-
end
-
-
1
def discount_value
-
if discount.negative? || discount > MAX_DISCOUNT_VALUE
-
errors.add(:discount, 'Discount value is out of bounds')
-
end
-
end
-
end
-
end
-
# module BxBlockDashboard
-
# class ApplicationRecord < BuilderBase::ApplicationRecord
-
# self.abstract_class = true
-
# end
-
# end
-
module BxBlockDashboard
-
class ApplicationRecord < BuilderBase::ApplicationRecord
-
self.abstract_class = true
-
end
-
end
-
-
module BxBlockDashboard
-
class Candidate < BxBlockDashboard::ApplicationRecord
-
def self.table_name_prefix
-
'bx_block_dashboard_'
-
#self.table_name = :bx_block_dashboard_candidates
-
end
-
-
def sub_attributres
-
[
-
{
-
type: "Interview with client",
-
quantity: "100"
-
},
-
{
-
type: "Submitted for feedback",
-
quantity: "70"
-
},
-
{
-
type: "Candidates expecting offer",
-
quantity: "50"
-
},
-
{
-
type: "Candidates accepted",
-
quantity:"40"
-
}
-
]
-
end
-
end
-
end
-
module BxBlockDashboardguests
-
class ApplicationRecord < BuilderBase::ApplicationRecord
-
self.abstract_class = true
-
end
-
end
-
module BxBlockDashboardguests
-
class Company < BxBlockDashboardguests::ApplicationRecord
-
self.table_name = :bx_block_dashboardguests_companies
-
has_one_attached :doc, dependent: :destroy
-
validates :company_name, presence: true
-
end
-
end
-
module BxBlockDashboardguests
-
class DashboardGuest < BuilderBase::ApplicationRecord
-
self.table_name = :bx_block_dashboardguests_dashboard_guests
-
belongs_to :company, class_name: "BxBlockDashboardguests::Company"
-
validates :invest_amount, presence: true
-
validates :date_of_invest, presence: true
-
end
-
end
-
1
module BxBlockDatastorage
-
1
class ApplicationRecord < BuilderBase::ApplicationRecord
-
1
self.abstract_class = true
-
end
-
end
-
1
module BxBlockDatastorage
-
1
class FileDocument < ApplicationRecord
-
1
self.table_name = :bx_block_datastorage_file_documents
-
-
1
belongs_to :account, class_name: 'AccountBlock::Account'
-
1
has_many_attached :attachments
-
1
validates :title, :description, presence: true
-
1
enum document_type: ["document", "certificate", "achievement"]
-
-
1
def document_file_url
-
file_array = []
-
if self.attachments.attached?
-
self.attachments.each do |file|
-
file_array << { file: Rails.application.routes.url_helpers.rails_blob_path(file, disposition: "attachment", only_path: true) }
-
end
-
end
-
file_array
-
end
-
end
-
end
-
module BxBlockDocumentopener2
-
class ApplicationRecord < BuilderBase::ApplicationRecord
-
self.abstract_class = true
-
end
-
end
-
module BxBlockDocumentstorage2
-
class ApplicationRecord < BuilderBase::ApplicationRecord
-
self.abstract_class = true
-
end
-
end
-
module BxBlockDownload
-
class ApplicationRecord < BuilderBase::ApplicationRecord
-
self.abstract_class = true
-
end
-
end
-
module BxBlockDownload
-
class Downloadable < BxBlockDownload::ApplicationRecord
-
self.table_name = :bx_block_download_downloadables
-
include Wisper::Publisher
-
-
has_many_attached :files
-
-
validates :files, :reference_id, :reference_type, presence: true
-
end
-
end
-
module BxBlockElasticsearch
-
def self.table_name_prefix
-
'bx_block_elasticsearch_'
-
end
-
end
-
module BxBlockElasticsearch
-
class ApplicationRecord < BuilderBase::ApplicationRecord
-
self.abstract_class = true
-
end
-
end
-
require "searchkick"
-
module BxBlockElasticsearch
-
class BxBlockElasticsearch::Article < ApplicationRecord
-
Searchkick.client_type = :elasticsearch
-
#Searchkick.client_type = :elasticsearch or :opensearch
-
searchkick
-
end
-
end
-
module BxBlockFavourites
-
class ApplicationRecord < BuilderBase::ApplicationRecord
-
self.abstract_class = true
-
end
-
end
-
module BxBlockFavourites
-
class Favourite < BxBlockFavourites::ApplicationRecord
-
self.table_name = :favourites
-
-
belongs_to :favouriteable, polymorphic: true
-
end
-
end
-
# == Schema Information
-
#
-
# Table name: addressables
-
#
-
# id :bigint not null, primary key
-
# shipment_id :bigint not null
-
# address :text
-
# address2 :text
-
# city :string
-
# country :string
-
# email :string
-
# name :string
-
# phone :string
-
# instructions :text
-
# type :string
-
# created_at :datetime not null
-
# updated_at :datetime not null
-
#
-
module BxBlockFedexIntegration
-
class Addressable < BxBlockFedexIntegration::ApplicationRecord
-
self.table_name = :addressables
-
-
belongs_to :shipment, class_name: "BxBlockFedexIntegration::Shipment"
-
has_one :arrival_window,
-
class_name: "BxBlockFedexIntegration::ArrivalWindow", dependent: :destroy
-
has_one :coordinate,
-
class_name: "BxBlockFedexIntegration::Coordinate", dependent: :destroy
-
-
accepts_nested_attributes_for :arrival_window, :coordinate
-
end
-
end
-
module BxBlockFedexIntegration
-
class ApplicationRecord < BuilderBase::ApplicationRecord
-
self.abstract_class = true
-
end
-
end
-
# == Schema Information
-
#
-
# Table name: arrival_windows
-
#
-
# id :bigint not null, primary key
-
# begin_at :datetime
-
# end_at :datetime
-
# exclude_begin :boolean default(TRUE)
-
# exclude_end :boolean default(TRUE)
-
# created_at :datetime not null
-
# updated_at :datetime not null
-
# addressable_id :integer
-
#
-
module BxBlockFedexIntegration
-
class ArrivalWindow < BxBlockFedexIntegration::ApplicationRecord
-
self.table_name = :arrival_windows
-
-
END_AT_DAYS = 10.freeze
-
-
belongs_to :addressable, class_name: "BxBlockFedexIntegration::Addressable"
-
-
after_initialize :set_end_at
-
-
private
-
-
def set_end_at
-
self.end_at ||= begin_at + END_AT_DAYS.days if begin_at.present?
-
end
-
end
-
end
-
# == Schema Information
-
#
-
# Table name: cod_values
-
#
-
# id :bigint not null, primary key
-
# shipment_id :bigint not null
-
# amount :float
-
# currency :string default("RS")
-
# created_at :datetime not null
-
# updated_at :datetime not null
-
#
-
module BxBlockFedexIntegration
-
class CodValue < BxBlockFedexIntegration::ApplicationRecord
-
self.table_name = :cod_values
-
-
belongs_to :shipment, class_name: "BxBlockFedexIntegration::Shipment"
-
end
-
end
-
# == Schema Information
-
#
-
# Table name: coordinates
-
#
-
# id :bigint not null, primary key
-
# latitude :string
-
# longitude :string
-
# created_at :datetime not null
-
# updated_at :datetime not null
-
# addressable_id :integer
-
#
-
module BxBlockFedexIntegration
-
class Coordinate < BxBlockFedexIntegration::ApplicationRecord
-
self.table_name = :coordinates
-
-
belongs_to :addressable, class_name: "BxBlockFedexIntegration::Addressable"
-
end
-
end
-
# == Schema Information
-
#
-
# Table name: create_shipments
-
#
-
# id :bigint not null, primary key
-
# auto_assign_drivers :boolean default(FALSE)
-
# requested_by :string
-
# shipper_id :string
-
# waybill :string
-
# created_at :datetime not null
-
# updated_at :datetime not null
-
#
-
module BxBlockFedexIntegration
-
class CreateShipment < BxBlockFedexIntegration::ApplicationRecord
-
self.table_name = :create_shipments
-
-
has_many :shipments, class_name: "BxBlockFedexIntegration::Shipment", dependent: :destroy
-
-
accepts_nested_attributes_for :shipments
-
-
after_initialize :set_default_values
-
-
private
-
-
def set_default_values
-
self.requested_by = ["development","test"].include?(Rails.env) ?
-
'Profile_67ff1b39-37f0-4f6c-aac7-71cf844b331a' : ENV['_525K_PROFILE_ID']
-
self.shipper_id = ["development","test"].include?(Rails.env) ?
-
'Profile_67ff1b39-37f0-4f6c-aac7-71cf844b331a' : ENV['_525K_PROFILE_ID']
-
end
-
end
-
end
-
# == Schema Information
-
#
-
# Table name: addressables
-
#
-
# id :bigint not null, primary key
-
# shipment_id :bigint not null
-
# address :text
-
# address2 :text
-
# city :string
-
# country :string
-
# email :string
-
# name :string
-
# phone :string
-
# instructions :text
-
# type :string
-
# created_at :datetime not null
-
# updated_at :datetime not null
-
#
-
module BxBlockFedexIntegration
-
class Delivery < Addressable
-
end
-
end
-
# == Schema Information
-
#
-
# Table name: dimensions
-
#
-
# id :bigint not null, primary key
-
# item_id :bigint not null
-
# height :float
-
# length :float
-
# width :float
-
# created_at :datetime not null
-
# updated_at :datetime not null
-
#
-
module BxBlockFedexIntegration
-
class Dimension < BxBlockFedexIntegration::ApplicationRecord
-
self.table_name = :dimensions
-
-
belongs_to :item, class_name: "BxBlockFedexIntegration::Item"
-
end
-
end
-
# == Schema Information
-
#
-
# Table name: items
-
#
-
# id :bigint not null, primary key
-
# shipment_id :bigint not null
-
# ref_id :string
-
# weight :float
-
# quantity :integer
-
# stackable :boolean default(TRUE)
-
# item_type :integer default("PALLET")
-
# created_at :datetime not null
-
# updated_at :datetime not null
-
#
-
module BxBlockFedexIntegration
-
class Item < BxBlockFedexIntegration::ApplicationRecord
-
self.table_name = :items
-
-
belongs_to :shipment, class_name: "BxBlockFedexIntegration:Shipment"
-
has_one :dimension, class_name: "BxBlockFedexIntegration::Dimension", dependent: :destroy
-
-
enum item_type: %w(PALLET BOX OTHER)
-
-
accepts_nested_attributes_for :dimension
-
-
after_initialize :set_ref_id
-
-
private
-
-
def set_ref_id
-
self.ref_id = loop do
-
random_id = "item-#{SecureRandom.hex(10)}"
-
break random_id unless Item.exists?(ref_id: random_id)
-
end
-
end
-
end
-
end
-
# == Schema Information
-
#
-
# Table name: addressables
-
#
-
# id :bigint not null, primary key
-
# shipment_id :bigint not null
-
# address :text
-
# address2 :text
-
# city :string
-
# country :string
-
# email :string
-
# name :string
-
# phone :string
-
# instructions :text
-
# type :string
-
# created_at :datetime not null
-
# updated_at :datetime not null
-
#
-
module BxBlockFedexIntegration
-
class Pickup < Addressable
-
end
-
end
-
# == Schema Information
-
#
-
# Table name: shipments
-
#
-
# id :bigint not null, primary key
-
# create_shipment_id :bigint not null
-
# ref_id :string
-
# full_truck :boolean default(FALSE)
-
# load_description :text
-
# created_at :datetime not null
-
# updated_at :datetime not null
-
#
-
module BxBlockFedexIntegration
-
class Shipment < BxBlockFedexIntegration::ApplicationRecord
-
self.table_name = :shipments
-
-
belongs_to :create_shipment, class_name: "BxBlockFedexIntegration::CreateShipment"
-
has_one :cod_value, dependent: :destroy,
-
class_name: "BxBlockFedexIntegration::CodValue"
-
has_one :shipment_value,
-
class_name: "BxBlockFedexIntegration::ShipmentValue", dependent: :destroy
-
has_one :delivery,
-
class_name: "BxBlockFedexIntegration::Delivery", dependent: :destroy
-
has_one :pickup,
-
class_name: "BxBlockFedexIntegration::Pickup", dependent: :destroy
-
has_many :items, class_name: "BxBlockFedexIntegration::Item", dependent: :destroy
-
-
accepts_nested_attributes_for :cod_value, :shipment_value, :delivery, :pickup, :items
-
-
after_initialize :set_ref_id
-
-
private
-
-
def set_ref_id
-
self.ref_id = loop do
-
random_id = "shipment-#{SecureRandom.hex(10)}"
-
break random_id unless Shipment.exists?(ref_id: random_id)
-
end
-
end
-
end
-
end
-
# == Schema Information
-
#
-
# Table name: shipment_values
-
#
-
# id :bigint not null, primary key
-
# shipment_id :bigint not null
-
# amount :float
-
# currency :string
-
# created_at :datetime not null
-
# updated_at :datetime not null
-
#
-
module BxBlockFedexIntegration
-
class ShipmentValue < BxBlockFedexIntegration::ApplicationRecord
-
self.table_name = :shipment_values
-
-
belongs_to :shipment, class_name: "BxBlockFedexIntegration::Shipment"
-
end
-
end
-
module BxBlockForgotPassword
-
class ApplicationRecord < BuilderBase::ApplicationRecord
-
self.abstract_class = true
-
end
-
end
-
1
module BxBlockInvoice
-
1
class ApplicationRecord < BuilderBase::ApplicationRecord
-
1
self.abstract_class = true
-
end
-
end
-
module BxBlockInvoice
-
class BillToAddress < ApplicationRecord
-
self.table_name = :bx_block_invoice_bill_to_addresses
-
end
-
end
-
1
module BxBlockInvoice
-
1
class Company < ApplicationRecord
-
1
self.table_name = :bx_block_invoice_companies
-
end
-
end
-
1
module BxBlockInvoice
-
1
class Invoice < ApplicationRecord
-
1
self.table_name = :bx_block_invoice_invoices
-
1
belongs_to :order, class_name: "BxBlockInvoice::Order"
-
1
has_many :invoice_items, class_name: "BxBlockInvoice::InvoiceItem", foreign_key: :invoice_id
-
1
has_one_attached :invoice_pdf
-
1
before_save :generate_pdf
-
-
1
def generate_pdf
-
html = ActionController::Base.new.render_to_string(template: "bx_block_invoices/generate_invoice_pdf.html.erb",
-
orientation: "Landscape", page_size: "Letter", formats: :pdf, background: true, locals: {invoice: self})
-
pdf = WickedPdf.new.pdf_from_string(html, filename: "Invoice_#{invoice_number}.pdf",
-
type: "application/pdf")
-
invoice_pdf.attach(io: StringIO.new(pdf), filename: "Invoice_#{invoice_number}.pdf",
-
content_type: "application/pdf")
-
end
-
end
-
end
-
module BxBlockInvoice
-
class InvoiceItem < ApplicationRecord
-
self.table_name = :bx_block_invoice_invoice_items
-
end
-
end
-
module BxBlockInvoice
-
class Item < ApplicationRecord
-
self.table_name = :bx_block_invoice_items
-
belongs_to :order, class_name: "BxBlockInvoice::Order", optional: true
-
end
-
end
-
# frozen_string_literal: true
-
-
1
module BxBlockInvoice
-
1
class Order < BxBlockInvoice::ApplicationRecord
-
1
self.table_name = :bx_block_invoice_orders
-
1
has_many :items, class_name: "BxBlockInvoice::Item", foreign_key: :order_id
-
1
has_many :invoices, class_name: "BxBlockInvoice::Invoice", foreign_key: :order_id
-
1
belongs_to :company, class_name: "BxBlockInvoice::Company", foreign_key: :company_id
-
1
has_many :bill_to_addresses, class_name: "BxBlockInvoice::BillToAddress", foreign_key: :order_id
-
1
accepts_nested_attributes_for :items, allow_destroy: true
-
1
accepts_nested_attributes_for :invoices, allow_destroy: true
-
1
accepts_nested_attributes_for :bill_to_addresses, allow_destroy: true
-
-
1
after_create :generate_invoice
-
-
1
def assign_total_amount
-
items.pluck(:item_unit_price).compact.sum
-
end
-
-
1
def generate_invoice
-
bill_to_addresses.each do |bill_to_address|
-
@invoice = invoices.build(
-
company_address: company&.address,
-
company_city: company&.city,
-
company_zip_code: company&.zip_code,
-
company_phone_number: company&.phone_number,
-
bill_to_name: customer_name,
-
bill_to_company_name: bill_to_address.company_name,
-
bill_to_address: bill_to_address&.address,
-
bill_to_city: bill_to_address&.city,
-
bill_to_zip_code: bill_to_address&.zip_code,
-
bill_to_phone_number: bill_to_address&.phone_number,
-
bill_to_email: bill_to_address&.email, total_amount: assign_total_amount,
-
invoice_number: 6.times.map { rand(10) }.join,
-
invoice_date: order_date
-
)
-
@invoice.save
-
items = self.items
-
items.each do |item|
-
@invoice.invoice_items.create(item_id: item.id)
-
end
-
end
-
end
-
end
-
end
-
module BxBlockInvoices
-
def self.table_name_prefix
-
"bx_block_invoices_"
-
end
-
end
-
module BxBlockLandingpage2
-
class ApplicationRecord < BuilderBase::ApplicationRecord
-
self.abstract_class = true
-
end
-
end
-
module BxBlockLanguageOptions
-
class ApplicationMessage < ApplicationRecord
-
self.table_name = :application_messages
-
-
translates :message, touch: true
-
-
validates :name, presence: true, uniqueness: {case_sensitive: false}
-
translation_class.validates :message,
-
presence: { message: "EN translation message can't be blank" },
-
if: -> (trans) { trans.locale == :en }
-
-
accepts_nested_attributes_for :translations, allow_destroy: true
-
-
def self.translation_message(key)
-
application_message = BxBlockLanguageOptions::ApplicationMessage.find_by(name: key)
-
if application_message.present?
-
return application_message.message if application_message.message.present?
-
"Translation not present for key: #{key}, locale: #{Globalize.locale()}"
-
else
-
"Translation not present for key: #{key}"
-
end
-
end
-
-
def self.set_message_for(key, locale, message)
-
application_message = BxBlockLanguageOptions::ApplicationMessage.find_by(name: key)
-
if application_message.present?
-
application_message.update!(locale: locale, message: message)
-
else
-
raise "Translation not present for key: #{key}"
-
end
-
end
-
end
-
end
-
module BxBlockLanguageOptions
-
class ApplicationRecord < BuilderBase::ApplicationRecord
-
self.abstract_class = true
-
end
-
end
-
module BxBlockLanguageOptions
-
class ContentLanguage < ApplicationRecord
-
self.table_name = :contents_languages
-
-
belongs_to :account, class_name: "AccountBlock::Account"
-
belongs_to :language, class_name: "BxBlockLanguageOptions::Language",
-
foreign_key: "language_options_language_id"
-
-
end
-
end
-
module BxBlockLanguageOptions
-
class Language < ApplicationRecord
-
self.table_name = :language_options_languages
-
-
validates :name, :language_code, uniqueness: {case_sensitive: false}, presence: true
-
-
scope :content_languages, -> { where("is_content_language is true") }
-
scope :app_languages, -> { where("is_app_language is true") }
-
-
has_many :contents_languages,
-
class_name: "BxBlockLanguageOptions::ContentLanguage",
-
join_table: "contents_languages", dependent: :destroy
-
has_many :accounts,
-
class_name: "AccountBlock::Account",
-
through: :contents_languages, join_table: "contents_languages"
-
-
after_commit :update_available_locales
-
-
private
-
-
def update_available_locales
-
BxBlockLanguageOptions::SetAvailableLocales.call
-
end
-
-
end
-
end
-
module BxBlockLike
-
class ApplicationRecord < BuilderBase::ApplicationRecord
-
self.abstract_class = true
-
end
-
end
-
module BxBlockLike
-
class Like < BxBlockLike::ApplicationRecord
-
self.table_name = :likes
-
-
belongs_to :likeable, polymorphic: true
-
-
after_create :create_notification
-
-
private
-
-
def create_notification
-
liked_type = (likeable_type == "AccountBlock::Account") ? "profile" : "post"
-
account = AccountBlock::Account.find(like_by_id)
-
BxBlockPushNotifications::PushNotification.create(
-
account_id: like_by_id,
-
push_notificable_type: "AccountBlock::Account",
-
push_notificable_id: likeable.id,
-
remarks: "#{account.first_name} #{account.last_name} \
-
liked your #{liked_type}"
-
)
-
end
-
end
-
end
-
1
module BxBlockLocation
-
1
class ApplicationRecord < BuilderBase::ApplicationRecord
-
1
self.abstract_class = true
-
end
-
end
-
1
module BxBlockLocation
-
1
class Location < ApplicationRecord
-
1
self.table_name = :locations
-
1
reverse_geocoded_by :latitude, :longitude
-
-
1
belongs_to :van, class_name: 'BxBlockLocation::Van'
-
end
-
end
-
module BxBlockLocation
-
class Van < AccountBlock::ApplicationRecord
-
self.table_name = :vans
-
-
has_one :location,
-
class_name: 'BxBlockLocation::Location',
-
dependent: :destroy
-
has_one :service_provider,
-
class_name: 'BxBlockLocation::VanMember',
-
dependent: :destroy, foreign_key: 'account_id'
-
has_many :assistants,
-
class_name: 'BxBlockLocation::VanMember',
-
dependent: :destroy, foreign_key: 'account_id'
-
has_many :van_members, class_name: 'BxBlockLocation::VanMember', dependent: :destroy
-
has_many :reviews, as: :reviewable, class_name: 'BxBlockReviews::Review',dependent: :destroy
-
-
has_one_attached :main_photo
-
has_many_attached :galleries
-
-
before_create :offline_van
-
after_create :assign_location
-
-
accepts_nested_attributes_for :van_members, :service_provider, :assistants
-
-
validates :name, presence: true, uniqueness: true
-
-
def service_provider
-
BxBlockRolesPermissions::Role.find_by_name('admin').accounts.joins(
-
'JOIN van_members ON van_members.account_id = accounts.id'
-
).where(
-
accounts: { van_members: {van_id: self.id} }
-
)
-
end
-
-
def available_vans vans
-
available_service_provider = Array.new
-
service_providers_for_vans(vans).each do |service_provider|
-
unless contains_booked_slot_time(service_provider)
-
van = BxBlockLocation::Van.joins(:van_members).where(
-
'van_members.account_id = ?', service_provider.id
-
).first
-
-
available_service_provider << van.location
-
else
-
next
-
end
-
end
-
available_service_provider
-
end
-
-
private
-
-
def contains_booked_slot_time(service_provider)
-
contain_booked_slot_time = false
-
get_booked_slots(get_availability(service_provider)).each do |booked_slot|
-
if (booked_slot.start_time..booked_slot.end_time).cover?(Time.now) or
-
(booked_slot.start_time..booked_slot.end_time).cover?(Time.now + 1.hours)
-
contain_booked_slot_time = true
-
break
-
end
-
end
-
contain_booked_slot_time
-
end
-
-
def get_availability(service_provider)
-
BxBlockAppointmentManagement::Availability.where(
-
service_provider_id: service_provider.id,
-
availability_date: Date.today.strftime('%d/%m/%y')
-
).first
-
end
-
-
def get_booked_slots(availability)
-
BxBlockAppointmentManagement::BookedSlot.where(
-
service_provider_id: availability.service_provider.id,
-
booking_date: Date.today.strftime('%d/%m/%y')
-
).map{ |booked_slot| {
-
start_time: booked_slot.start_time.to_time, end_time: booked_slot.end_time.to_time
-
}
-
}
-
end
-
-
def service_providers_for_vans(vans)
-
BxBlockRolesPermissions::Role.find_by_name('admin').accounts.joins(
-
'JOIN van_members ON van_members.account_id = accounts.id'
-
).joins(
-
'JOIN availabilities ON availabilities.service_provider_id = accounts.id'
-
).where(
-
'availabilities.availability_date = ?', Date.today.strftime('%d/%m/%y')
-
).joins(
-
'JOIN vans on vans.id = van_members.van_id'
-
).where('vans.id = ?', vans.ids)
-
end
-
-
def assign_location
-
self.create_location() unless self.location.present?
-
end
-
-
def offline_van
-
self.is_offline = true
-
end
-
-
end
-
end
-
module BxBlockLocation
-
class VanMember < AccountBlock::ApplicationRecord
-
self.table_name = :van_members
-
-
belongs_to :van, class_name: 'BxBlockLocation::Van'
-
belongs_to :account, class_name: 'AccountBlock::Account'
-
end
-
end
-
module BxBlockLogin
-
class ApplicationRecord < BuilderBase::ApplicationRecord
-
self.abstract_class = true
-
end
-
end
-
module BxBlockMultipageforms2
-
class ApplicationRecord < BuilderBase::ApplicationRecord
-
self.abstract_class = true
-
end
-
end
-
1
module BxBlockMultipageforms2
-
1
class UserProfile < BuilderBase::ApplicationRecord
-
1
self.table_name = :bx_block_multipageforms2_user_profiles
-
1
validates :first_name, :last_name, :phone_number, :email, :gender, :country, :industry, :message, presence: true
-
-
1
enum industry: { education: 0, food: 1, marketing: 2 }
-
end
-
end
-
module BxBlockNavmenu
-
class ApplicationRecord < BuilderBase::ApplicationRecord
-
self.abstract_class = true
-
end
-
end
-
module BxBlockNavmenu
-
class NavigationMenu < BxBlockNavmenu::ApplicationRecord
-
self.table_name = :navigation_menus
-
end
-
end
-
module BxBlockOfflinebrowsing2
-
class ApplicationRecord < BuilderBase::ApplicationRecord
-
self.abstract_class = true
-
end
-
end
-
# frozen_string_literal: true
-
-
1
module BxBlockOrderManagement
-
1
class ApplicationRecord < BuilderBase::ApplicationRecord
-
1
self.abstract_class = true
-
end
-
end
-
# frozen_string_literal: true
-
-
# == Schema Information
-
#
-
# Table name: delivery_addresses
-
#
-
# id :bigint not null, primary key
-
# account_id :bigint not null
-
# address :string
-
# name :string
-
# flat_no :string
-
# zip_code :string
-
# phone_number :string
-
# deleted_at :datetime
-
# latitude :float
-
# longitude :float
-
# residential :boolean default(TRUE)
-
# city :string
-
# state_code :string
-
# country_code :string
-
# state :string
-
# country :string
-
# address_line_2 :string
-
# address_type :string default("home")
-
# address_for :string default("shipping")
-
# is_default :boolean default(FALSE)
-
# landmark :string
-
# created_at :datetime not null
-
# updated_at :datetime not null
-
#
-
module BxBlockOrderManagement
-
class DeliveryAddress < BxBlockOrderManagement::ApplicationRecord
-
self.table_name = :delivery_addresses
-
-
belongs_to :account, class_name: "AccountBlock::Account", optional: true
-
has_many :delivery_address_orders, dependent: :destroy
-
has_many :orders, through: :delivery_address_orders
-
-
validates :name, :flat_no, :address, :zip_code, :phone_number, presence: true
-
validates :phone_number, format: {
-
with: /^(?:\+?\d{1,3}\s*-?)?\(?(?:\d{3})?\)?[- ]?\d{3}[- ]?\d{4}$/,
-
multiline: true,
-
message: " is not valid"
-
}
-
validates :address_for, presence: true, inclusion: {
-
in: %w[shipping billing billing_and_shipping]
-
}
-
-
scope :rest_addresses, ->(address_id) { where.not(id: address_id) }
-
scope :billing_and_shipping, -> { where(address_for: "billing_and_shipping") }
-
scope :delivery_add, -> { where(address_for: %w[shipping billing_and_shipping]) }
-
end
-
end
-
# frozen_string_literal: true
-
-
# == Schema Information
-
#
-
# Table name: delivery_address_orders
-
#
-
# id :bigint not null, primary key
-
# order_id :bigint not null
-
# delivery_address_id :bigint not null
-
# created_at :datetime not null
-
# updated_at :datetime not null
-
#
-
module BxBlockOrderManagement
-
class DeliveryAddressOrder < BxBlockOrderManagement::ApplicationRecord
-
self.table_name = :delivery_address_orders
-
-
belongs_to :order, class_name: "BxBlockOrderManagement::Order", foreign_key: "order_management_order_id"
-
belongs_to :delivery_address
-
-
scope :address_ids, ->(ids) { where(delivery_address_id: ids) }
-
end
-
end
-
# frozen_string_literal: true
-
-
# == Schema Information
-
#
-
# Table name: orders
-
#
-
# id :bigint not null, primary key
-
# order_number :string
-
# amount :float
-
# created_at :datetime not null
-
# updated_at :datetime not null
-
# account_id :bigint
-
# coupon_code_id :bigint
-
# delivery_address_id :bigint
-
# sub_total :decimal(, ) default(0.0)
-
# total :decimal(, ) default(0.0)
-
# status :string
-
# applied_discount :decimal(, ) default(0.0)
-
# cancellation_reason :text
-
# order_date :datetime
-
# is_gift :boolean default(FALSE)
-
# placed_at :datetime
-
# confirmed_at :datetime
-
# in_transit_at :datetime
-
# delivered_at :datetime
-
# cancelled_at :datetime
-
# refunded_at :datetime
-
# source :string
-
# shipment_id :string
-
# delivery_charges :string
-
# tracking_url :string
-
# schedule_time :datetime
-
# payment_failed_at :datetime
-
# returned_at :datetime
-
# tax_charges :decimal(, ) default(0.0)
-
# deliver_by :integer
-
# tracking_number :string
-
# is_error :boolean default(FALSE)
-
# delivery_error_message :string
-
# payment_pending_at :datetime
-
# order_status_id :integer
-
# is_group :boolean default(TRUE)
-
# is_availability_checked :boolean default(FALSE)
-
# shipping_charge :decimal(, )
-
# shipping_discount :decimal(, )
-
# shipping_net_amt :decimal(, )
-
# shipping_total :decimal(, )
-
# total_tax :float
-
#
-
1
module BxBlockOrderManagement
-
1
class Order < BxBlockOrderManagement::ApplicationRecord
-
1
self.table_name = :order_management_orders
-
1
include PublicActivity::Model
-
50
tracked owner: proc { |controller, model| controller&.current_user }
-
-
1
ORDER_NO_FORMAT = "00000000"
-
-
1
belongs_to :account, class_name: "AccountBlock::Account"
-
1
belongs_to :coupon_code, class_name: "BxBlockCouponCg::CouponCode", optional: true
-
-
1
belongs_to :order_status, class_name: "BxBlockOrderManagement::OrderStatus", optional: true
-
-
1
has_one :order_transaction, foreign_key: "order_management_order_id"
-
-
1
has_many :order_items, dependent: :destroy, class_name: "BxBlockOrderManagement::OrderItem",
-
foreign_key: "order_management_order_id"
-
# has_many :catalogues, class_name: "BxBlockCatalogue::Catalogue", through: :order_items
-
1
has_many :ebooks, class_name: "BxBlockBulkUploading::Ebook", through: :order_items
-
1
has_many :bundle_managements, class_name: "BxBlockBulkUploading::BundleManagement", through: :order_items
-
-
# has_many :order_trackings, class_name: "OrderTracking", as: :parent
-
# has_many :trackings, through: :order_trackings
-
-
# has_many :delivery_address_orders, dependent: :destroy, foreign_key: "order_management_order_id"
-
# has_many :delivery_addresses, through: :delivery_address_orders
-
# scope :date_range_orders, lambda { |start_date, end_date|
-
# where("Date(created_at) BETWEEN ? AND ? AND charged = true ", start_date, end_date)
-
# }
-
-
1
validates :status, presence: true, inclusion: {
-
in: %w[
-
in_cart
-
created
-
placed
-
confirmed
-
in_transit
-
delivered
-
cancelled
-
refunded
-
payment_failed
-
returned
-
payment_pending
-
]
-
}
-
-
1
accepts_nested_attributes_for :order_items, allow_destroy: true
-
-
1
enum deliver_by: %i[fedex]
-
-
1
before_save :set_status
-
1
before_create :add_order_number
-
-
1
include AASM
-
1
aasm column: "status" do
-
1
state :in_cart, initial: true
-
1
state :created, :placed, :confirmed, :in_transit, :delivered, :cancelled, :refunded,
-
:payment_failed, :returned, :payment_pending
-
-
1
event :in_cart do
-
1
transitions to: :in_cart
-
end
-
-
1
event :created do
-
1
transitions to: :created
-
end
-
-
1
event :pending_order do
-
1
transitions from: %i[in_cart created payment_failed],
-
to: :payment_pending,
-
after: proc { |*_args| update_state_process }
-
end
-
-
1
event :place_order do
-
1
transitions to: :placed, after: proc { |*_args| update_state_process }
-
end
-
-
1
event :confirm_order do
-
1
transitions to: :confirmed, after: proc { |*_args| update_state_process }
-
end
-
-
1
event :to_transit do
-
1
transitions to: :in_transit, after: proc { |*_args| update_state_process }
-
end
-
-
1
event :payment_failed do
-
1
transitions to: :payment_failed, after: proc { |*_args| update_state_process }
-
end
-
-
1
event :deliver_order do
-
1
transitions to: :delivered, after: proc { |*_args| update_state_process }
-
end
-
-
1
event :cancel_order do
-
1
transitions to: :cancelled, after: proc { |*_args| update_state_process }
-
end
-
-
1
event :refund_order do
-
1
transitions to: :refunded, after: proc { |*_args| update_state_process }
-
end
-
-
1
event :return_order do
-
1
transitions to: :returned, after: proc { |*_args| update_state_process }
-
end
-
-
# OrderStatus.new_statuses.each do |order_status|
-
# state order_status.status.to_s.downcase.to_sym
-
# end
-
end
-
-
1
EVENTS = %w[
-
pending_order!
-
place_order!
-
confirm_order!
-
to_transit!
-
deliver_order!
-
refund_order!
-
cancel_order!
-
payment_failed!
-
return_order!
-
].freeze
-
-
1
def update_state_process
-
StateProcess.new(self, aasm).call
-
end
-
-
1
def set_status
-
# check_holds
-
53
if (OrderStatus::USER_STATUSES.include? status) && !order_status_id_changed?
-
47
order_status = OrderStatus.find_or_create_by(status: status) if status.present?
-
47
self.order_status_id = order_status.id unless order_status_id == order_status.id
-
end
-
53
if (order_items.pluck(:order_status_id).uniq != [order_status_id]) && is_group?
-
53
order_items&.update(order_status_id: order_status_id)
-
end
-
end
-
-
1
def total_price
-
3
(order_items.sum(:total_price) - applied_discount)&.round(2)
-
end
-
-
1
def total_after_shipping_charge
-
# applied_shipping_charge = ShippingCharge.last
-
3
applied_shipping_charge = {below: 500.0, charge: 50.0}
-
3
if applied_shipping_charge.present?
-
3
charge = applied_shipping_charge[:charge]
-
3
self.shipping_charge = charge
-
3
self.shipping_discount = if total <= applied_shipping_charge[:below]
-
3
0.0
-
else
-
charge
-
end
-
else
-
self.shipping_charge = 0.0
-
self.shipping_discount = 0.0
-
end
-
3
self.shipping_total = shipping_charge - shipping_discount
-
3
self.shipping_net_amt = shipping_charge - shipping_discount
-
3
self.total = total + shipping_total
-
end
-
-
1
def total_after_tax_charge
-
# applied_tax = Tax.last
-
3
applied_tax = {tax_percentage: 18}
-
3
if applied_tax.present?
-
3
tax_charge = ((total.to_f * applied_tax[:tax_percentage].to_f) / 100).to_f.round(2)
-
3
self.total_tax = tax_charge
-
3
self.total = total.round(2) + total_tax
-
end
-
end
-
-
1
def sub_total_price
-
3
order_items.sum(:total_price)&.round(2)
-
end
-
-
1
def full_order_cancelled?
-
order_items.cancelled.count == order_items.count
-
end
-
-
1
def add_order_number
-
46
self.order_number = "OD#{Order.next_order_number}"
-
end
-
-
1
def self.next_order_number
-
46
return Order::ORDER_NO_FORMAT.succ if Order.count.zero?
-
-
25
Order.last.order_number.split("OD")[1].succ
-
end
-
end
-
end
-
# rubocop:enable Metrics/MethodLength, Metrics/AbcSize, Metrics/BlockLength, Metrics/ClassLength, Metrics/CyclomaticComplexity
-
# frozen_string_literal: true
-
-
# == Schema Information
-
#
-
# Table name: order_items
-
#
-
# id :bigint not null, primary key
-
# order_id :bigint not null
-
# quantity :integer
-
# unit_price :decimal(, )
-
# total_price :decimal(, )
-
# old_unit_price :decimal(, )
-
# status :string
-
# created_at :datetime not null
-
# updated_at :datetime not null
-
# catalogue_id :bigint not null
-
# catalogue_variant_id :bigint not null
-
# order_status_id :integer
-
# placed_at :datetime
-
# confirmed_at :datetime
-
# in_transit_at :datetime
-
# delivered_at :datetime
-
# cancelled_at :datetime
-
# refunded_at :datetime
-
# manage_placed_status :boolean default(FALSE)
-
# manage_cancelled_status :boolean default(FALSE)
-
#
-
1
module BxBlockOrderManagement
-
1
class OrderItem < BxBlockOrderManagement::ApplicationRecord
-
1
self.table_name = :order_items
-
-
1
belongs_to :order, class_name: "BxBlockOrderManagement::Order", foreign_key: "order_management_order_id"
-
1
belongs_to :catalogue, class_name: "BxBlockCatalogue::Catalogue", optional: true
-
-
1
belongs_to :ebook, class_name: "BxBlockBulkUploading::Ebook", optional: true
-
1
belongs_to :bundle_management, class_name: "BxBlockBulkUploading::BundleManagement", optional: true
-
# belongs_to :catalogue_variant,
-
# class_name: "BxBlockCatalogue::CatalogueVariant", optional: true
-
-
1
belongs_to :order_status, class_name: "BxBlockOrderManagement::OrderStatus", optional: true
-
-
1
has_many :order_trackings, class_name: "OrderTracking", as: :parent
-
1
has_many :trackings, through: :order_trackings
-
-
1
scope :get_records, ->(ids) { where(order_management_order_id: ids) }
-
-
1
include AASM
-
1
aasm column: "status" do
-
1
state :in_cart, initial: true
-
1
state :created, :placed, :confirmed, :in_transit, :delivered, :cancelled,
-
:refunded, :payment_failed, :returned, :payment_pending
-
-
1
event :in_cart do
-
1
transitions to: :in_cart
-
end
-
-
1
event :created do
-
1
transitions to: :created
-
end
-
-
1
event :pending_order do
-
1
transitions from: %i[in_cart created payment_failed],
-
to: :payment_pending,
-
after: proc { |*_args| update_state_process }
-
end
-
-
1
event :place_order do
-
1
transitions to: :placed,
-
after: proc { |*_args| update_state_process }
-
end
-
-
1
event :confirm_order do
-
1
transitions to: :confirmed,
-
after: proc { |*_args| update_state_process }
-
end
-
-
1
event :to_transit do
-
1
transitions to: :in_transit,
-
after: proc { |*_args| update_state_process }
-
end
-
-
1
event :payment_failed do
-
1
transitions to: :payment_failed,
-
after: proc { |*_args| update_state_process }
-
end
-
-
1
event :deliver_order do
-
1
transitions to: :delivered,
-
after: proc { |*_args| update_state_process }
-
end
-
-
1
event :cancel_order do
-
1
transitions to: :cancelled,
-
after: proc { |*_args| update_state_process }
-
end
-
-
1
event :refund_order do
-
1
transitions to: :refunded,
-
after: proc { |*_args| update_state_process }
-
end
-
-
1
event :return_order do
-
1
transitions to: :returned,
-
after: proc { |*_args| update_state_process }
-
end
-
end
-
-
1
before_save :update_prices
-
1
before_save :set_item_status, if: :order_status_id_changed?
-
# after_save :update_product_stock, if: :order_status_id_changed?
-
-
1
def update_prices
-
28
if from_warehouse
-
28
self.unit_price = ebook&.price || bundle_management&.total_pricing
-
28
self.total_price = order_item_total
-
end
-
end
-
-
1
def set_item_status
-
4
if status.present? && !order_status.present?
-
self.order_status_id = OrderStatus.find_or_create_by(
-
status: status
-
).id
-
end
-
4
event_name = order_status&.event_name
-
4
send("#{event_name}!") unless order_status&.status == status
-
end
-
-
# def is_order_paced
-
# !manage_placed_status && order_status.present? &&
-
# order_status.status == "placed"
-
# end
-
-
# def is_order_cancelled
-
# !manage_cancelled_status && order_status.present? &&
-
# order_status.status == "cancelled"
-
# end
-
-
# def update_product_stock
-
# product = catalogue_variant.present? ? catalogue_variant : catalogue
-
# if is_order_paced
-
# stock_qty = (product.stock_qty.to_i - quantity)
-
# block_qty = product.block_qty.to_i - quantity.to_i
-
# product.update!(stock_qty: stock_qty, block_qty: block_qty)
-
# if product.instance_of?(BxBlockCatalogue::CatalogueVariant)
-
# product.catalogue.update(
-
# stock_qty: product.catalogue.stock_qty - quantity,
-
# block_qty: product.catalogue.block_qty.to_i - quantity.to_i
-
# )
-
# end
-
# update(manage_placed_status: true)
-
# elsif is_order_cancelled
-
# # block_qty = product.block_qty.to_i - self.quantity.to_i
-
# product.update(stock_qty: product.stock_qty.to_i + quantity)
-
# if product.instance_of?(BxBlockCatalogue::CatalogueVariant)
-
# product.catalogue.update(stock_qty: product.catalogue.stock_qty + quantity)
-
# end
-
# update(manage_cancelled_status: true)
-
# end
-
# end
-
-
1
def from_warehouse
-
28
ebook.present? ? ebook : bundle_management
-
end
-
-
# def price
-
# if catalogue_variant.present?
-
# if catalogue_variant.on_sale?
-
# catalogue_variant.sale_price
-
# else
-
# catalogue_variant.price
-
# end
-
# else
-
# catalogue&.on_sale? ? catalogue.sale_price : catalogue.price
-
# end
-
# end
-
-
1
def order_item_total
-
# (quantity * ebook&.price) || (quantity * bundle_management&.total_pricing)
-
28
if ebook.present? && ebook.price.present?
-
25
ebook_price = ebook.price
-
else
-
3
ebook_price = 0
-
end
-
-
28
if bundle_management.present? && bundle_management.total_pricing.present?
-
23
bundle_price = bundle_management.total_pricing
-
else
-
5
bundle_price = 0
-
end
-
-
28
ebook_price + bundle_price
-
end
-
-
1
def update_state_process
-
StateProcess.new(self, aasm).call
-
end
-
end
-
end
-
# rubocop:enable Metrics/MethodLength, Naming/PredicateName, Metrics/AbcSize, Metrics/BlockLength, Metrics/ClassLength
-
# frozen_string_literal: true
-
-
# == Schema Information
-
#
-
# Table name: order_statuses
-
#
-
# id :bigint not null, primary key
-
# name :string
-
# status :string
-
# active :boolean default(TRUE)
-
# event_name :string
-
# message :string
-
# created_at :datetime not null
-
# updated_at :datetime not null
-
#
-
1
module BxBlockOrderManagement
-
1
class OrderStatus < BxBlockOrderManagement::ApplicationRecord
-
1
self.table_name = :order_statuses
-
1
include PublicActivity::Model
-
22
tracked owner: proc { |controller, model| controller&.current_user }
-
-
1
has_many :orders, class_name: "Order"
-
1
has_many :order_items, class_name: "OrderItem"
-
-
1
validates_uniqueness_of :status
-
-
1
before_save :add_status
-
-
# scope :new_statuses, lambda {
-
# where.not(status: %i[
-
# in_cart
-
# created
-
# placed
-
# confirmed
-
# in_transit
-
# delivered
-
# cancelled
-
# refunded
-
# payment_failed
-
# returned
-
# payment_pending
-
# ])
-
# }
-
-
1
USER_STATUSES = %w[
-
in_cart
-
created
-
placed
-
payment_failed
-
payment_pending
-
].freeze
-
-
1
CUSTOM_STATUSES = %w[
-
in_cart
-
created
-
placed
-
confirmed
-
in_transit
-
delivered
-
cancelled
-
refunded
-
payment_failed
-
returned
-
payment_pending
-
].freeze
-
-
1
private
-
-
1
def add_status
-
21
self.status = name.to_s.downcase.parameterize.underscore unless status.present?
-
21
self.event_name = name.to_s.downcase.parameterize.underscore unless event_name.present?
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
# == Schema Information
-
#
-
# Table name: order_trackings
-
#
-
# id :bigint not null, primary key
-
# parent_type :string
-
# parent_id :bigint
-
# tracking_id :integer
-
# created_at :datetime not null
-
# updated_at :datetime not null
-
#
-
module BxBlockOrderManagement
-
class OrderTracking < BxBlockOrderManagement::ApplicationRecord
-
self.table_name = :order_trackings
-
include PublicActivity::Model
-
tracked owner: proc { |controller, model| controller&.current_user }
-
belongs_to :parent, polymorphic: true
-
belongs_to :tracking
-
-
scope :parent_orders, -> { where(parent_type: "Order") }
-
scope :parent_order_items, -> { where(parent_type: "OrderItem") }
-
end
-
end
-
# frozen_string_literal: true
-
-
# == Schema Information
-
#
-
# Table name: order_transactions
-
#
-
# id :bigint not null, primary key
-
# account_id :bigint not null
-
# order_id :bigint not null
-
# charge_id :string
-
# amount :integer
-
# currency :string
-
# charge_status :string
-
# created_at :datetime not null
-
# updated_at :datetime not null
-
#
-
1
module BxBlockOrderManagement
-
1
class OrderTransaction < BxBlockOrderManagement::ApplicationRecord
-
1
self.table_name = :order_transactions
-
1
include PublicActivity::Model
-
1
tracked owner: proc { |controller, model| controller&.current_user }
-
1
belongs_to :account, class_name: "AccountBlock::Account"
-
1
belongs_to :order, class_name: "BxBlockOrderManagement::Order", foreign_key: "order_management_order_id"
-
end
-
end
-
# frozen_string_literal: true
-
-
module BxBlockOrderManagement
-
class PrintPrice < BxBlockOrderManagement::ApplicationRecord
-
validates_uniqueness_of :page_size, scope: :colors
-
include PublicActivity::Model
-
tracked owner: proc { |controller, model| controller&.current_user }
-
scope :single_side, ->(page_size, colors) {
-
where("LOWER(page_size) = ? AND LOWER(colors) =? ", page_size.downcase, colors.downcase)
-
}
-
scope :double_side, lambda { |page_size, colors|
-
where("LOWER(page_size) = ? AND LOWER(colors) =? ", page_size.downcase, colors.downcase)
-
}
-
end
-
end
-
# frozen_string_literal: true
-
-
# == Schema Information
-
#
-
# Table name: trackings
-
#
-
# id :bigint not null, primary key
-
# status :string
-
# tracking_number :string
-
# date :datetime
-
# created_at :datetime not null
-
# updated_at :datetime not null
-
#
-
module BxBlockOrderManagement
-
class Tracking < BxBlockOrderManagement::ApplicationRecord
-
self.table_name = :trackings
-
include PublicActivity::Model
-
tracked owner: proc { |controller, model| controller&.current_user }
-
has_many :order_trackings, dependent: :destroy
-
-
has_many :orders, through: :order_trackings, source: :parent, source_type: "Order"
-
has_many :order_items, through: :order_trackings, source: :parent, source_type: "OrderItem"
-
-
TRACKING_NO_FORMAT = "00000000"
-
-
before_create :add_tracking_number
-
-
def add_tracking_number
-
self.tracking_number = "TR#{Tracking.next_tracking_number}"
-
end
-
-
def self.next_tracking_number
-
return Tracking::TRACKING_NO_FORMAT.succ if Tracking.count.zero?
-
-
Tracking.last.tracking_number.split("TR")[1].succ
-
end
-
end
-
end
-
module BxBlockPayments
-
class ApplicationRecord < ActiveRecord::Base
-
self.abstract_class = true
-
end
-
end
-
module BxBlockPayments
-
class Transaction < BxBlockPayments::ApplicationRecord
-
self.table_name = :transactions
-
-
enum status: { failed: 0, success: 1 }
-
belongs_to :account, class_name: 'AccountBlock::Account'
-
-
end
-
end
-
# frozen_string_literal: true
-
-
module BxBlockPlan
-
class ApplicationRecord < BuilderBase::ApplicationRecord
-
self.abstract_class = true
-
end
-
end
-
# frozen_string_literal: true
-
-
module BxBlockPlan
-
class Plan < BxBlockPlan::ApplicationRecord
-
self.table_name = :plans
-
enum duration: ['3 Months', '6 Months', '1 Year']
-
-
validate :create_only_three, on: :create
-
-
private
-
-
def create_only_three
-
errors.add(:base, "You can't create more than three plans.") if BxBlockPlan::Plan.count > 2
-
end
-
end
-
end
-
module BxBlockPosts
-
class ApplicationRecord < BuilderBase::ApplicationRecord
-
self.abstract_class = true
-
end
-
end
-
module BxBlockPosts
-
class Post < BxBlockPosts::ApplicationRecord
-
self.table_name = :posts
-
ActiveSupport.run_load_hooks(:post, self)
-
-
if ENV['TEMPLATEAPP_DATABASE']
-
include PublicActivity::Model
-
tracked owner: proc { |controller, _| controller&.current_user }
-
end
-
IMAGE_CONTENT_TYPES = %w(image/jpg image/jpeg image/png)
-
-
has_many_attached :images, dependent: :destroy
-
-
belongs_to :category,
-
class_name: 'BxBlockCategories::Category'
-
-
belongs_to :sub_category,
-
class_name: 'BxBlockCategories::SubCategory',
-
foreign_key: :sub_category_id, optional: true
-
-
belongs_to :account, class_name: 'AccountBlock::Account'
-
has_many_attached :media, dependent: :destroy
-
-
validates_presence_of :body
-
validates :media,
-
size: { between: 1..3.megabytes }, content_type: IMAGE_CONTENT_TYPES
-
-
end
-
end
-
# frozen_string_literal: true
-
-
1
module BxBlockProfile
-
1
class ApplicationRecord < BuilderBase::ApplicationRecord
-
1
self.abstract_class = true
-
1
self.table_name = 'bx_block_profile_application_records'
-
end
-
end
-
module BxBlockProfile
-
class Associated < ApplicationRecord
-
self.table_name = :bx_block_profile_associateds
-
has_many :associated_projects, class_name: "BxBlockProfile::AssociatedProject"
-
end
-
end
-
module BxBlockProfile
-
class AssociatedProject < ApplicationRecord
-
self.table_name = :bx_block_profile_associated_projects
-
belongs_to :project, class_name: "BxBlockProfile::Project"
-
belongs_to :associated, class_name: "BxBlockProfile::Associated"
-
end
-
end
-
module BxBlockProfile
-
class Award < ApplicationRecord
-
self.table_name = :bx_block_profile_awards
-
belongs_to :profile, class_name: "BxBlockProfile::Profile"
-
validates :profile_id, presence: true
-
end
-
end
-
module BxBlockProfile
-
class CareerExperience < ApplicationRecord
-
self.table_name = :bx_block_profile_career_experiences
-
belongs_to :profile, class_name: "BxBlockProfile::Profile"
-
has_many :career_experience_industrys, class_name: "BxBlockProfile::CareerExperienceIndustry"
-
has_many :career_experience_employment_types, class_name: "BxBlockProfile::CareerExperienceEmploymentType"
-
has_many :career_experience_system_experiences, class_name: "BxBlockProfile::CareerExperienceSystemExperience"
-
end
-
end
-
module BxBlockProfile
-
class CareerExperienceEmploymentType < ApplicationRecord
-
self.table_name = :bx_block_profile_career_experience_employment_types
-
belongs_to :career_experience, class_name: "BxBlockProfile::CareerExperience"
-
belongs_to :employment_type, class_name: "BxBlockProfile::EmploymentType"
-
end
-
end
-
module BxBlockProfile
-
class CareerExperienceIndustry < ApplicationRecord
-
self.table_name = :bx_block_profile_career_experience_industry
-
belongs_to :career_experience, class_name: "BxBlockProfile::CareerExperience"
-
belongs_to :industry, class_name: "BxBlockProfile::Industry"
-
end
-
end
-
module BxBlockProfile
-
class CareerExperienceSystemExperience < ApplicationRecord
-
self.table_name = :bx_block_profile_career_experience_system_experiences
-
belongs_to :career_experience, class_name: "BxBlockProfile::CareerExperience"
-
belongs_to :system_experience, class_name: "BxBlockProfile::SystemExperience"
-
end
-
end
-
module BxBlockProfile
-
class Course < ApplicationRecord
-
self.table_name = :bx_block_profile_courses
-
belongs_to :profile, class_name: "BxBlockProfile::Profile"
-
validates :profile_id, presence: true
-
end
-
end
-
module BxBlockProfile
-
class CurrentAnnualSalary < ApplicationRecord
-
self.table_name = :bx_block_profile_current_annual_salaries
-
has_many :current_annual_salary_current_status, class_name: "BxBlockProfile::CurrentAnnualSalaryCurrentStatus"
-
end
-
end
-
module BxBlockProfile
-
class CurrentAnnualSalaryCurrentStatus < ApplicationRecord
-
self.table_name = :bx_block_profile_current_annual_salary_current_status
-
belongs_to :current_status, class_name: "BxBlockProfile::CurrentStatus"
-
belongs_to :current_annual_salary, class_name: "BxBlockProfile::CurrentAnnualSalary"
-
end
-
end
-
module BxBlockProfile
-
class CurrentStatus < ApplicationRecord
-
self.table_name = :bx_block_profile_current_status
-
belongs_to :profile, class_name: "BxBlockProfile::Profile"
-
has_many :current_status_industrys, class_name: "BxBlockProfile::CurrentStatusIndustry"
-
has_many :current_status_employment_types, class_name: "BxBlockProfile::CurrentStatusEmploymentType"
-
has_many :current_annual_salary_current_status, class_name: "BxBlockProfile::CurrentAnnualSalaryCurrentStatus"
-
end
-
end
-
module BxBlockProfile
-
class CurrentStatusEmploymentType < ApplicationRecord
-
self.table_name = :bx_block_profile_current_status_employment_types
-
belongs_to :current_status, class_name: "BxBlockProfile::CurrentStatus"
-
belongs_to :employment_type, class_name: "BxBlockProfile::EmploymentType"
-
end
-
end
-
module BxBlockProfile
-
class CurrentStatusIndustry < ApplicationRecord
-
self.table_name = :bx_block_profile_current_status_industries
-
belongs_to :current_status, class_name: "BxBlockProfile::CurrentStatus"
-
belongs_to :industry, class_name: "BxBlockProfile::Industry"
-
end
-
end
-
module BxBlockProfile
-
class CustomUserProfileFields < ApplicationRecord
-
self.table_name = :bx_block_profile_custom_user_profile_fields
-
-
validates :name, presence: true, uniqueness: true
-
validates :field_type, presence: true, inclusion: { in: ['text', 'password', 'email', 'number', 'range', 'date','time','datetime','checkbox', 'radio','select','textarea','file','search'], message: "%{value} is not a valid field type" }
-
end
-
end
-
module BxBlockProfile
-
class Degree < ApplicationRecord
-
self.table_name = :bx_block_profile_degrees
-
has_many :degree_educational_qualifications,
-
class_name: "BxBlockProfile::DegreeEducationalQualification"
-
end
-
end
-
module BxBlockProfile
-
class DegreeEducationalQualification < ApplicationRecord
-
self.table_name = :bx_block_profile_degree_educational_qualifications
-
belongs_to :degree, class_name: "BxBlockProfile::Degree"
-
belongs_to :educational_qualification, class_name: "BxBlockProfile::EducationalQualification"
-
end
-
end
-
module BxBlockProfile
-
class EducationalQualification < ApplicationRecord
-
self.table_name = :bx_block_profile_educational_qualifications
-
belongs_to :profile, class_name: "BxBlockProfile::Profile"
-
has_many :degree_educational_qualifications, class_name: "BxBlockProfile::DegreeEducationalQualification"
-
has_many :educational_qualification_field_studys, class_name: "BxBlockProfile::EducationalQualificationFieldStudy"
-
end
-
end
-
module BxBlockProfile
-
class EducationalQualificationFieldStudy < ApplicationRecord
-
self.table_name = :bx_block_profile_educational_qualification_field_study
-
belongs_to :field_study, class_name: "BxBlockProfile::FieldStudy"
-
belongs_to :educational_qualification, class_name: "BxBlockProfile::EducationalQualification"
-
end
-
end
-
module BxBlockProfile
-
class EmploymentType < ApplicationRecord
-
self.table_name = :bx_block_profile_employment_types
-
has_many :current_status_employment_types, class_name: "BxBlockProfile::CurrentStatusEmploymentType"
-
has_many :career_experience_employment_types, class_name: "BxBlockProfile::CareerExperienceEmploymentType"
-
end
-
end
-
module BxBlockProfile
-
class FieldStudy < ApplicationRecord
-
self.table_name = :bx_block_profile_field_study
-
has_many :educational_qualification_field_studys, class_name: "BxBlockProfile::EducationalQualificationFieldStudy"
-
end
-
end
-
module BxBlockProfile
-
class Hobby < ApplicationRecord
-
self.table_name = :bx_block_profile_hobbies_and_interests
-
belongs_to :profile, class_name: "BxBlockProfile::Profile"
-
validates :profile_id, presence: true
-
end
-
end
-
module BxBlockProfile
-
class Industry < ApplicationRecord
-
self.table_name = :bx_block_profile_industries
-
has_many :current_status_industrys, class_name: "BxBlockProfile::CurrentStatusIndustry"
-
has_many :career_experience_industrys, class_name: "BxBlockProfile::CareerExperienceIndustry"
-
end
-
end
-
module BxBlockProfile
-
class Language < ApplicationRecord
-
self.table_name = :bx_block_profile_languages
-
belongs_to :profile, class_name: "BxBlockProfile::Profile"
-
validates :profile_id, presence: true
-
end
-
end
-
1
module BxBlockProfile
-
1
class Profile < ApplicationRecord
-
1
self.table_name = :bx_block_profile_profiles
-
-
1
has_one_attached :photo
-
1
has_one_attached :profile_video
-
1
belongs_to :account, class_name: "AccountBlock::Account"
-
# has_one :current_status, dependent: :destroy, class_name: "BxBlockProfile::CurrentStatus"
-
# accepts_nested_attributes_for :current_status, allow_destroy: true
-
# has_one :publication_patent,dependent: :destroy, class_name: "BxBlockProfile::PublicationPatent"
-
# accepts_nested_attributes_for :publication_patent, allow_destroy: true
-
# has_many :awards, dependent: :destroy, class_name: "BxBlockProfile::Award"
-
# accepts_nested_attributes_for :awards, allow_destroy: true
-
# has_many :hobbies, dependent: :destroy, class_name: "BxBlockProfile::Hobby"
-
# accepts_nested_attributes_for :hobbies, allow_destroy: true
-
# has_many :courses, dependent: :destroy, class_name: "BxBlockProfile::Course"
-
# accepts_nested_attributes_for :courses, allow_destroy: true
-
# has_many :test_score_and_courses,dependent: :destroy, class_name: "BxBlockProfile::TestScoreAndCourse"
-
# accepts_nested_attributes_for :test_score_and_courses, allow_destroy: true
-
# has_many :career_experiences,dependent: :destroy, class_name: "BxBlockProfile::CareerExperience"
-
# accepts_nested_attributes_for :career_experiences, allow_destroy: true
-
# has_one :video, class_name: "BxBlockVideolibrary::Video"
-
# has_many :educational_qualifications, dependent: :destroy,class_name: "BxBlockProfile::EducationalQualification"
-
# accepts_nested_attributes_for :educational_qualifications, allow_destroy: true
-
# has_many :projects,dependent: :destroy, class_name: "BxBlockProfile::Project"
-
# accepts_nested_attributes_for :projects, allow_destroy: true
-
# has_many :languages, class_name: "BxBlockProfile::Language"
-
# has_many :contacts, class_name: "BxBlockContactsintegration::Contact"
-
# has_many :jobs, class_name: "BxBlockJobListing::Job"
-
# has_many :applied_jobs, class_name: "BxBlockJobListing::AppliedJob"
-
# has_many :follows, class_name: "BxBlockJobListing::Follow"
-
# has_many :company_pages, through: :follows , class_name: "BxBlockJoblisting::CompanyPage"
-
# has_many :interview_schedules, class_name: "BxBlockCalendar::InterviewSchedule"
-
# has_and_belongs_to_many :company_pages, dependent: :destroy,
-
#class_name: "BxBlockJobListing::CompanyPage",
-
# join_table: :profiles_company_pages
-
#validates :profile_role, presence: true
-
# enum profile_role: [:jobseeker, :recruiter]
-
# validate :profile_validation
-
-
# Added associations for qr code and profile bio
-
# has_one :qr_code, as: :qrable, class_name: "BxBlockQrCodes::QrCode"
-
# has_one :profile_bio, class_name: "BxBlockProfileBio::ProfileBio"
-
# accepts_nested_attributes_for :profile_bio
-
# accepts_nested_attributes_for :qr_code
-
-
# serialize :user_profile_data, Hash
-
-
# after_initialize do
-
# self.user_profile_data ||= {}
-
# end
-
-
# if ActiveRecord::Base.connection&.table_exists?('bx_block_profile_custom_user_profile_fields')
-
# def self.custom_user_profile_field_names
-
# BxBlockProfile::CustomUserProfileFields.all&.pluck(:name)
-
# end
-
-
# store_accessor :user_profile_data, *custom_user_profile_field_names
-
-
# BxBlockProfile::CustomUserProfileFields.all&.each do |column|
-
# define_method column.name do
-
# user_profile_data[column.name]
-
# end
-
-
# define_method "#{column.name}=" do |value|
-
# user_profile_data[column.name] = value
-
# end
-
# end
-
# end rescue nil
-
-
-
# def reload_custom_fields
-
# custom_user_profile_fields = BxBlockProfile::CustomUserProfileFields.all&.pluck(:name)
-
# custom_user_profile_fields.each do |name|
-
# unless self.user_profile_data[name].present?
-
# # store_accessor :user_profile_data, name
-
# self.class.send(:define_method, name) do
-
# user_profile_data[name]
-
# end
-
# self.class.send(:define_method, "#{name}=") do |value|
-
# user_profile_data[name] = value
-
# end
-
# end
-
-
# end
-
# end
-
-
# private
-
-
# def profile_validation
-
# if account && account.profiles.count > 2
-
# errors.add(:profiles, "for an account can not exceed count of 2")
-
# end
-
# end
-
-
# def photo_present?
-
# errors.add(:photo, :blank) unless photo.attached?
-
# end
-
-
end
-
end
-
-
-
module BxBlockProfile
-
class Project < ApplicationRecord
-
self.table_name = :bx_block_profile_projects
-
belongs_to :profile, class_name: "BxBlockProfile::Profile"
-
has_many :associated_projects, class_name: "BxBlockProfile::AssociatedProject"
-
end
-
end
-
module BxBlockProfile
-
class PublicationPatent < ApplicationRecord
-
self.table_name = :bx_block_profile_publication_patents
-
belongs_to :profile, class_name: "BxBlockProfile::Profile"
-
end
-
end
-
module BxBlockProfile
-
class SystemExperience < ApplicationRecord
-
self.table_name = :bx_block_profile_system_experiences
-
has_many :career_experience_system_experiences, class_name: "BxBlockProfile::CareerExperienceSystemExperience"
-
end
-
end
-
module BxBlockProfile
-
class TestScoreAndCourse < ApplicationRecord
-
self.table_name = :bx_block_profile_test_score_and_courses
-
belongs_to :profile, class_name: "BxBlockProfile::Profile"
-
validates :profile_id, presence: true
-
end
-
end
-
# frozen_string_literal: true
-
-
module BxBlockProfileBio
-
# achivement model
-
class Achievement < BxBlockProfileBio::ApplicationRecord
-
self.table_name = :achievements
-
include Wisper::Publisher
-
belongs_to :profile_bio
-
-
URL_REGEXP = %r{^(http|https)://[a-z0-9]+([\-.]{1}[a-z0-9]+)*\.[a-z]{2,5}(:[0-9]{1,5})?(/.*)?$}i.freeze
-
validates :url,
-
format: {
-
with: URL_REGEXP,
-
message: 'is invalid,
-
format example: http/https://www.test.com',
-
multiline: true
-
}, allow_blank: true
-
end
-
end
-
# frozen_string_literal: true
-
-
module BxBlockProfileBio
-
# base model
-
class ApplicationRecord < BuilderBase::ApplicationRecord
-
self.abstract_class = true
-
end
-
end
-
# frozen_string_literal: true
-
-
module BxBlockProfileBio
-
# carrer model
-
class Career < BxBlockProfileBio::ApplicationRecord
-
self.table_name = :careers
-
include Wisper::Publisher
-
-
belongs_to :profile_bio
-
-
enum sector: %i[Government Private], _prefix: :sector
-
end
-
end
-
# frozen_string_literal: true
-
-
module BxBlockProfileBio
-
# education model
-
class Education < BxBlockProfileBio::ApplicationRecord
-
self.table_name = :educations
-
-
include Wisper::Publisher
-
belongs_to :profile_bio
-
end
-
end
-
# frozen_string_literal: true
-
-
module BxBlockProfileBio
-
# prefences model
-
class Preference < BxBlockProfileBio::ApplicationRecord
-
self.table_name = :preferences
-
-
include Wisper::Publisher
-
# belongs_to :profile_bio
-
belongs_to :account, class_name: 'AccountBlock::Account'
-
-
enum smoking: %i[Yes No Sometimes], _prefix: :smoking
-
enum drinking: %i[Yes No Occasionally], _prefix: :drinking
-
enum religion: %i[Buddhist Christian Hindu Jain Muslim Sikh], _prefix: :religion
-
enum height_type: %i[cm inches foot], _prefix: :height_type
-
enum body_type: %i[Athletic Average Fat Slim], _prefix: :body_type
-
enum seeking: %i[Male Female Both], _prefix: :seeking
-
end
-
end
-
# frozen_string_literal: true
-
-
# rubocop:disable Naming/VariableNumber, Lint/IneffectiveAccessModifier, Metrics/AbcSize, Naming/MemoizedInstanceVariableName, Metrics/MethodLength, Lint/UselessAssignment, Metrics/ClassLength, Style/GlobalVars
-
module BxBlockProfileBio
-
# profile bio model
-
class ProfileBio < BxBlockProfileBio::ApplicationRecord
-
self.table_name = :profile_bios
-
-
belongs_to :account, class_name: 'AccountBlock::Account'
-
-
has_many :educations, dependent: :destroy
-
has_many :achievements, dependent: :destroy
-
has_many :careers, dependent: :destroy
-
-
enum marital_status: %i[Single In-Relationship Engaged Married Divorced Widowed], _prefix: :marital_status
-
enum smoking: %i[Yes No Sometimes], _prefix: :smoking
-
enum drinking: %i[Yes No Occasionally], _prefix: :drinking
-
enum height_type: %i[cm inches foot], _prefix: :height_type
-
enum weight_type: %i[kg pounds(lbs)], _prefix: :weight_type
-
-
enum body_type: %i[Athletic Average Fat Slim], _prefix: :body_type
-
enum mother_tougue: %i[
-
Arabic Bengali Chinese English French German Gujarati Hindi Indonesian Italian
-
Japanese Malayalam Marathi Nepali Portuguese Punjabi Russian Spanish Swahili
-
Tamil Telugu Turkish Urdu
-
], _prefix: :mother_tougue
-
enum religion: %i[Buddhist Christian Hindu Jain Muslim Sikh], _prefix: :religion
-
enum zodiac: %i[Aquarius Aries Cancer Capricorn Gemini Leo Libra Pisces Sagittarius Scorpio Taurus Virgo],
-
_prefix: :zodiac
-
-
validates :languages, presence: true
-
-
accepts_nested_attributes_for :educations, :achievements, :careers, allow_destroy: true
-
-
INTERESTS_VALUES = [
-
'Sports', 'Fitness', 'Cooking', 'Traveling', 'Politics', 'Adventures', 'Music',
-
'Pets', 'Mountains', 'Beaches', 'Cooking', 'Nature', 'Photography', 'Dancing',
-
'Painting', 'Pets', 'Music', 'Puzzles', 'Gardening', 'Reading Books', 'Handicrafts',
-
'Movies', 'Night Outs', 'Stargazing', 'Internet', 'Surfing', 'Traveling',
-
'Chit Chat', 'Sports', 'Adventures', 'Trekking', 'Hiking', 'Yoga', 'Workouts',
-
'Baking', 'Binge-Watching', 'Calligraphy', 'Blogging', 'Writing', 'Drama',
-
'Home Improving', 'Journaling', 'Knitting', 'Martial Arts', 'Miniature Art',
-
'Poetry', 'Sewing', 'Sketching', 'Singing', 'Video Gaming', 'Wood Carving',
-
'Astronomy', 'Bird Watching', 'Fishing', 'Swimming', 'Nature'
-
].freeze
-
-
PERSONALITY_VALUES = [
-
'Extrovert', 'Introvert', 'Creative', 'Angry', 'Cool', 'Emotional', 'Practical',
-
'Rules Breaker', 'Stick To Rules', 'Optimistic', 'Pessimist', 'Hard Work',
-
'Smart Work', 'Spendthrift', 'Miser', 'Good Listener', 'Talks a Lot', 'Childish',
-
'Matured', 'Patient', 'Impatient', 'Competitive', 'Relaxed', 'Last-Minute Person',
-
'Pre-Planner', 'Foodie', 'Book Bug', 'Shopaholic', 'Morning Person', 'Night Owl'
-
].freeze
-
-
validates_intersection_of :personality, in: PERSONALITY_VALUES, message: 'invalid personality'
-
validates_intersection_of :interests, in: INTERESTS_VALUES, message: 'invalid interests'
-
end
-
end
-
# rubocop:enable Naming/VariableNumber, Lint/IneffectiveAccessModifier, Metrics/AbcSize, Naming/MemoizedInstanceVariableName, Metrics/MethodLength, Lint/UselessAssignment, Metrics/ClassLength, Style/GlobalVars
-
# frozen_string_literal: true
-
-
module BxBlockProfileBio
-
# view profiler model
-
# rubocop:disable Lint/IneffectiveAccessModifier
-
class ViewProfile < BxBlockProfileBio::ApplicationRecord
-
self.table_name = :view_profiles
-
-
include Wisper::Publisher
-
-
# belongs_to :account, class_name: 'AccountBlock::Account'
-
belongs_to :viewer, foreign_key: :view_by_id, class_name: 'AccountBlock::Account'
-
belongs_to :profile_bio,
-
foreign_key: :profile_bio_id,
-
class_name: 'BxBlockProfileBio::ProfileBio'
-
-
after_create :create_notification
-
-
attr_accessor :mutual_friends
-
-
private
-
-
def self.mutual_friend(current_account_id, profiles)
-
profiles.each do |profile|
-
mutual_friends = fetch_mutual_friends(profile, current_account_id, profiles)
-
profile.mutual_friends = mutual_friends || []
-
end
-
end
-
-
def self.fetch_mutual_friends(profile, current_account_id, _profiles)
-
sender_friends = fetch_friends(profile.view_by_id)
-
receiver_friends = fetch_friends(current_account_id)
-
-
mutual_friend_ids = sender_friends.flatten.uniq - [profile.view_by_id] &
-
receiver_friends.flatten.uniq - [current_account_id]
-
AccountBlock::Account.where(id: mutual_friend_ids)
-
end
-
-
def self.fetch_friends(id_to_find_with)
-
BxBlockRequestManagement::Request.where(
-
'(sender_id=? or account_id=?) and status=?',
-
id_to_find_with, id_to_find_with, 0
-
).pluck(:account_id, :sender_id)
-
end
-
-
def create_notification
-
user_account = AccountBlock::Account.find(view_by_id)
-
message = "#{user_account.first_name} #{user_account.last_name} has viewed your profile"
-
BxBlockPushNotifications::PushNotification.create(account_id: view_by_id,
-
push_notificable_type: 'AccountBlock::Account',
-
push_notificable_id: profile_bio.account_id,
-
notify_type: 'viewed_profile',
-
remarks: message)
-
end
-
end
-
# rubocop:enable Lint/IneffectiveAccessModifier
-
end
-
module BxBlockPushNotifications
-
class ApplicationRecord < BuilderBase::ApplicationRecord
-
self.abstract_class = true
-
end
-
end
-
module BxBlockPushNotifications
-
class PushNotification < ApplicationRecord
-
require 'fcm'
-
self.table_name = :push_notifications
-
-
belongs_to :push_notificable, polymorphic: true
-
belongs_to :account, class_name: "AccountBlock::Account"
-
validates :remarks, presence:true
-
before_create :send_push_notification
-
-
def send_push_notification
-
if push_notificable.activated && push_notificable.device_id &&
-
push_notificable.privacy_setting["#{notify_type}".to_sym]
-
fcm_client = FCM.new(ENV['FCM_SEVER_KEY']) # set your FCM_SERVER_KEY
-
options = { priority: 'high',
-
data: {
-
message: remarks,
-
notify_type: "#{notify_type}",
-
account_id: account_id
-
},
-
notification: {
-
body: remarks,
-
sound: 'default'
-
}
-
}
-
registration_id = push_notificable.device_id
-
# A registration ID looks something like:
-
#“dAlDYuaPXes:APA91bFEipxfcckxglzRo8N1SmQHqC6g8SWFATWBN9orkwgvTM57kmlFOUYZAmZKb4XGGOOL
-
#9wqeYsZHvG7GEgAopVfVupk_gQ2X5Q4Dmf0Cn77nAT6AEJ5jiAQJgJ_LTpC1s64wYBvC”
-
fcm_client.send(registration_id, options)
-
end
-
rescue Exception => e
-
e
-
end
-
end
-
end
-
module BxBlockRequestManagement
-
class ApplicationRecord < BuilderBase::ApplicationRecord
-
self.abstract_class = true
-
end
-
end
-
module BxBlockRequestManagement
-
class Request < BxBlockRequestManagement::ApplicationRecord
-
self.table_name = :requests
-
-
before_create do
-
self.status = "pending"
-
end
-
-
belongs_to :sender, foreign_key: :sender_id, class_name: "AccountBlock::Account"
-
belongs_to :account_group, foreign_key: :account_group_id,
-
class_name: "BxBlockAccountGroups::Group"
-
-
enum status: %i[pending accepted rejected], _prefix: :status
-
validates :rejection_reason, presence: true, on: :change_status_rejected
-
-
scope :pending, -> { where(status: "pending") }
-
scope :accepted, -> { where(status: "accepted") }
-
scope :rejected, -> { where(status: "rejected") }
-
end
-
end
-
1
module BxBlockRolesPermissions
-
1
class ApplicationRecord < BuilderBase::ApplicationRecord
-
1
self.abstract_class = true
-
end
-
end
-
1
module BxBlockRolesPermissions
-
1
class Role < ApplicationRecord
-
1
self.table_name = :roles
-
-
1
has_many :accounts, class_name: "AccountBlock::Account", dependent: :destroy
-
-
1
validates_presence_of :name
-
# validates_uniqueness_of :name
-
-
end
-
end
-
module BxBlockSettings
-
class ApplicationRecord < BuilderBase::ApplicationRecord
-
self.abstract_class = true
-
end
-
end
-
module BxBlockSettings
-
class Setting < ApplicationRecord
-
-
self.table_name = :settings
-
-
end
-
end
-
module BxBlockShoppingCart
-
class ApplicationRecord < BuilderBase::ApplicationRecord
-
self.abstract_class = true
-
end
-
end
-
module BxBlockShoppingCart
-
class Order < ApplicationRecord
-
include Wisper::Publisher
-
self.table_name = :shopping_cart_orders
-
-
BUFFER_TIME = 20 # in minute
-
-
# order status are
-
# upcomming = 'scheduled', ongoing = 'on_going', history = 'cancelled or completed
-
enum status: {"scheduled" => 0, "on_going" => 1, "cancelled" => 2, "completed" => 3}
-
-
has_many :order_items, class_name: "BxBlockShoppingCart::OrderItem"
-
belongs_to :address, class_name: "BxBlockAddress::Address", optional: true
-
belongs_to :customer, class_name: "AccountBlock::Account", foreign_key: :customer_id
-
-
validate :check_order_status, if: proc { |a| !a.new_record? }
-
-
before_create :assign_default_order_status
-
-
scope :todays_order, -> { where(slot_start_time: Date.today.strftime("%d/%m/%y")) }
-
scope :completed_order, -> { where(status: "completed") }
-
scope :completed_cancelled, -> { where(status: ["completed", "cancelled"]) }
-
private
-
-
def assign_default_order_status
-
self.status = "scheduled"
-
end
-
-
def check_order_status
-
if status_was == "completed"
-
errors.add(
-
:invalid_request, "Your order is finished, you can not update it now"
-
)
-
end
-
end
-
end
-
end
-
module BxBlockShoppingCart
-
class OrderItem < ApplicationRecord
-
self.table_name = :shopping_cart_order_items
-
belongs_to :order, class_name: "BxBlockShoppingCart::Order", foreign_key: :order_id
-
belongs_to :catalogue, class_name: "BxBlockCatalogue::Catalogue", foreign_key: :catalogue_id
-
-
before_save :assign_price_to_order_item
-
after_save :update_order_total
-
after_destroy :update_order_total
-
-
validate :order_can_be_updated
-
-
def order_can_be_updated
-
if ["cancelled", "completed"].include?(order.status)
-
errors.add(:order, "has already been #{order.status}")
-
end
-
end
-
-
def assign_price_to_order_item
-
self.price = catalogue.sale_price.to_f
-
end
-
-
def update_order_total
-
order.update(
-
total_fees: calculate_total_fees,
-
total_items: count_total_items,
-
total_tax: calculate_total_tax
-
)
-
end
-
-
def calculate_total_fees
-
order.order_items.map { |item| item.price * item.quantity }.sum
-
end
-
-
def count_total_items
-
order.order_items.map { |item| item.quantity }.sum
-
end
-
-
def calculate_total_tax
-
order.order_items.map { |item| item.quantity * item.taxable_value }.reject(&:blank?).sum
-
end
-
end
-
end
-
module BxBlockSplashscreen4
-
class ApplicationRecord < BuilderBase::ApplicationRecord
-
self.abstract_class = true
-
end
-
end
-
module BxBlockSplitpayments
-
class ApplicationRecord < BuilderBase::ApplicationRecord
-
self.abstract_class = true
-
end
-
end
-
module BxBlockSplitpayments
-
class Order < BxBlockSplitpayments::ApplicationRecord
-
include Wisper::Publisher
-
self.table_name = :bx_block_splitpayments_orders
-
-
def self.complete_order(order_detail)
-
@transaction = BxBlockPayments::Transaction.where(order_id: order_detail.id).last
-
@order = BxBlockShoppingCart::Order.find_by(id: order_detail.id)
-
bank_amount_details = []
-
amount = []
-
@order.poc_services.where.not(completed_at: nil).each do |poc_service|
-
@account = AccountBlock::Account.find_by(id: poc_service.poc_id)
-
@sub_account_id = @account&.bank_accounts&.last&.ccavenue_bank_account_id
-
split_amount = poc_service.earning
-
if @account.present? && @sub_account_id.present?
-
bank_amount_details << {:splitAmount=>split_amount.to_f.round(2), :subAccId=>@sub_account_id}
-
amount << split_amount.to_f.round(2)
-
else
-
bank_amount_details = []
-
end
-
end
-
if bank_amount_details.blank?
-
@order.update_column(:split_detail, "Bank Account Details should be present.")
-
elsif @transaction.present? && ((@transaction.ccavenue_status == "Success") || (@transaction.ccavenue_status == "success")) && amount.any? && (Time.now > (@transaction.created_at + 45.minutes))
-
mer_comm = @order.total_final_amt - amount.sum.to_f.round(2)
-
params_data = {"command": "createSplitPayout", "version": 1.2}
-
@data = {"split_tdr_charge_type"=>"A", "reference_no"=>@transaction.ccavenue_payment_id, "merComm"=>mer_comm, "split_data_list"=>bank_amount_details}
-
@order.update_column(:split_account_detail, @data.to_json)
-
response = CcAvenue::Ccavenueapi.new.refund_order(@data, params_data)
-
BxBlockSplitpayments::Order.split_response(@order, response, @transaction)
-
else
-
@order.update_column(:split_detail, "there is some error in split payment")
-
end
-
end
-
-
def self.split_response(order, response, transaction)
-
json_response = JSON.parse(response)["Create_Split_Payout_Result"] rescue {}
-
if json_response["status"] == 0
-
order_is_split = true
-
transaction_is_split = true
-
else
-
order_is_split = false
-
transaction_is_split = false
-
end
-
order.update_column(:split_detail, json_response.to_json)
-
order.update_column(:is_split, order_is_split)
-
transaction.update(is_split: transaction_is_split, split_detail: json_response.to_json)
-
end
-
end
-
end
-
module BxBlockStripeIntegration
-
class ApplicationRecord < ActiveRecord::Base
-
self.abstract_class = true
-
end
-
end
-
module BxBlockStripeIntegration
-
class PaymentIntent
-
attr_reader :id, :amount, :amount_capturable, :amount_details, :amount_received, :charges,
-
:client_secret, :confirmation_method, :created, :currency, :customer, :payment_method,
-
:payment_method_types
-
-
def initialize(stripe_payment_intent)
-
@id = stripe_payment_intent[:id]
-
@amount = stripe_payment_intent[:amount]
-
@amount_capturable = stripe_payment_intent[:amount_capturable]
-
@amount_details = stripe_payment_intent[:amount_details]
-
@amount_received = stripe_payment_intent[:amount_received]
-
@charges = stripe_payment_intent[:charges]
-
@client_secret = stripe_payment_intent[:client_secret]
-
@confirmation_method = stripe_payment_intent[:confirmation_method]
-
@created = stripe_payment_intent[:created]
-
@currency = stripe_payment_intent[:currency]
-
@customer = stripe_payment_intent[:customer]
-
@payment_method = stripe_payment_intent[:payment_method]
-
@payment_method_types = stripe_payment_intent[:payment_method_types]
-
end
-
end
-
end
-
module BxBlockStripeIntegration
-
class PaymentMethod
-
attr_reader :id, :billing_details, :card, :customer, :created
-
-
def initialize(stripe_payment_method)
-
@id = stripe_payment_method[:id]
-
@billing_details = stripe_payment_method[:billing_details]
-
@card = stripe_payment_method[:card]
-
@customer = stripe_payment_method[:customer]
-
@created = stripe_payment_method[:created]
-
end
-
end
-
end
-
1
module BxBlockTermsAndConditions
-
1
class ApplicationRecord < ActiveRecord::Base
-
1
self.abstract_class = true
-
end
-
end
-
1
module BxBlockTermsAndConditions
-
1
class TermsAndCondition < ApplicationRecord
-
1
has_many :user_terms_and_conditions,
-
class_name: "BxBlockTermsAndConditions::UserTermAndCondition",
-
dependent: :destroy, foreign_key: :terms_and_condition_id
-
1
has_many :accounts, through: :user_terms_and_conditions
-
1
validates :name, presence: true
-
1
validates :description, presence: true, length: { maximum: 5000 }
-
1
validate :only_one_entry_allowed
-
-
1
def get_accepted_accounts
-
1
BxBlockTermsAndConditions::UserTermAndCondition
-
.joins(:account)
-
.select("accounts.*,bx_block_terms_and_conditions_user_term_and_conditions.*")
-
.where(terms_and_condition_id: id, is_accepted: true)
-
end
-
-
1
def only_one_entry_allowed
-
29
if BxBlockTermsAndConditions::TermsAndCondition.exists? && !self.persisted?
-
15
errors.add(:base, 'Only one entry is allowed, please delete the existing one to create a new entry.')
-
end
-
end
-
-
1
class << self
-
1
private
-
-
1
def self.image_url(image)
-
if image.attached?
-
if Rails.env.development? || Rails.env.test?
-
Rails.application.routes.url_helpers.rails_blob_url(image, only_path: true)
-
else
-
image.service_url&.split("?")&.first
-
end
-
end
-
end
-
end
-
end
-
end
-
1
module BxBlockTermsAndConditions
-
1
class UserTermAndCondition < ApplicationRecord
-
1
self.table_name = :bx_block_terms_and_conditions_user_term_and_conditions
-
-
1
belongs_to :account, class_name: "AccountBlock::Account"
-
1
belongs_to :terms_and_condition, class_name: "BxBlockTermsAndConditions::TermsAndCondition"
-
end
-
end
-
module BxBlockWordlookup2
-
class ApplicationRecord < BuilderBase::ApplicationRecord
-
self.abstract_class = true
-
end
-
end
-
# frozen_string_literal: true
-
-
class ApplicationPolicy
-
attr_reader :user, :record
-
-
def initialize(user, record)
-
@user = user
-
@record = record
-
end
-
-
def index?
-
true
-
end
-
-
def show?
-
scope.where(id: record.id).exists?
-
end
-
-
def create?
-
true
-
end
-
-
def new?
-
create?
-
end
-
-
def update?
-
true
-
end
-
-
def edit?
-
update?
-
end
-
-
def destroy?
-
false
-
end
-
-
def scope
-
Pundit.policy_scope!(user, record.class)
-
end
-
-
class Scope
-
attr_reader :user, :scope
-
-
def initialize(user, scope)
-
@user = user
-
@scope = scope
-
end
-
-
def resolve
-
scope
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
module BxBlockComments
-
class ApplicationPolicy < ::ApplicationPolicy
-
end
-
end
-
# frozen_string_literal: true
-
-
module BxBlockComments
-
class CommentPolicy < ::BxBlockComments::ApplicationPolicy
-
def index?
-
true
-
end
-
-
def show?
-
true
-
end
-
-
def create?
-
true
-
end
-
-
def destroy?
-
true
-
end
-
-
def update?
-
true
-
end
-
end
-
end
-
1
module AccountBlock
-
1
class AccountSerializer < BuilderBase::BaseSerializer
-
1
attributes(:full_phone_number, :guardian_email,:guardian_name, :email, :activated, :is_reset, :publication_house_name, :school_id, :teacher_unique_id, :student_unique_id)
-
1
attribute :role do |acc|
-
13
acc.role&.name
-
end
-
-
1
attribute :school_name do |acc|
-
13
acc.school&.name
-
end
-
-
1
attribute :name do |acc|
-
13
acc.first_name
-
end
-
-
1
attribute :student_details do |acc|
-
13
BxBlockCategories::StudentDetailsSerializer.new(acc)
-
end
-
-
1
attribute :teacher_details do |acc|
-
13
_class_division = acc.class_division
-
13
teacher = AccountBlock::Account.find_by_id(_class_division&.account_id)
-
13
BxBlockCategories::TeacherDetailsSerializer.new(teacher)
-
end
-
-
1
attribute :class_allocated do |acc|
-
13
class_division = BxBlockCategories::ClassDivision.where(account_id: acc.id)
-
13
BxBlockCategories::ClassAllocatedSerializer.new(class_division)
-
end
-
end
-
end
-
module AccountBlock
-
class CountryCodeAndFlagSerializer < BuilderBase::BaseSerializer
-
attributes :name, :emoji_flag
-
-
set_id do |object|
-
object.alpha2
-
end
-
-
attribute :country_code do |object|
-
object.nanp_prefix || object.country_code
-
end
-
end
-
end
-
module AccountBlock
-
class EmailAccountSerializer
-
include FastJsonapi::ObjectSerializer
-
-
attributes(:first_name, :last_name, :full_phone_number, :country_code, :phone_number, :guardian_email,:guardian_name,:guardian_contact_no, :email, :activated)
-
end
-
end
-
module AccountBlock
-
class SmsAccountSerializer
-
include FastJsonapi::ObjectSerializer
-
-
attributes(:first_name, :last_name, :full_phone_number, :country_code, :phone_number, :email, :activated)
-
end
-
end
-
module AccountBlock
-
class SmsOtpSerializer < BuilderBase::BaseSerializer
-
end
-
end
-
module AccountBlock
-
class SocialAccountSerializer
-
include FastJsonapi::ObjectSerializer
-
-
attributes(:first_name, :last_name, :full_phone_number, :country_code, :phone_number, :email, :activated)
-
end
-
end
-
module AccountBlock
-
class ValidateAvailableSerializer
-
include FastJsonapi::ObjectSerializer
-
-
attributes :activated
-
-
set_id do |object|
-
object.class.name.underscore
-
end
-
-
attribute :email do |object|
-
object.is_a?(EmailAccount) ? object.email : nil
-
end
-
-
attribute :phone_number do |object|
-
object.is_a?(SmsAccount) ? object.full_phone_number : nil
-
end
-
-
attribute :account_exists do |object|
-
object.id.present? ? true : false
-
end
-
end
-
end
-
1
module BuilderBase
-
1
class BaseSerializer
-
1
include FastJsonapi::ObjectSerializer
-
-
1
class << self
-
1
private
-
-
1
def base_url
-
ENV['BASE_URL'] || 'http://localhost:3000'
-
end
-
end
-
end
-
end
-
module BxBlockAccountGroups
-
class GroupSerializer < BuilderBase::BaseSerializer
-
attributes :name, :settings, :accounts
-
end
-
end
-
module BxBlockAddress
-
class AddressSerializer < BuilderBase::BaseSerializer
-
attributes(:latitude, :longitude, :address, :address_type)
-
end
-
end
-
module BxBlockAnnotations
-
class AnnotationSerializer < BuilderBase::BaseSerializer
-
-
attributes *[
-
:title,
-
:description,
-
:account
-
]
-
end
-
end
-
module BxBlockAppointmentManagement
-
class ServiceProviderAvailabilitySerializer < BuilderBase::BaseSerializer
-
attributes :id, :availability_date
-
-
attribute :time_slots do |object|
-
slots_for(object)
-
end
-
-
class << self
-
private
-
-
def slots_for availability
-
availability.slots_list
-
end
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
module BxBlockAttachment
-
class FileAttachmentSerializer < BuilderBase::BaseSerializer
-
attributes(:name, :description, :embeded_code, :tag, :content_type, :thumnail, :is_active, :created_at,
-
:updated_at, :created_by)
-
-
attribute :url do |object|
-
url_for object
-
end
-
-
class << self
-
private
-
-
def url_for(object)
-
object&.attachment&.service_url if object&.attachment&.attached?
-
end
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
module BxBlockBulkUploading
-
class AttachmentSerializer < BuilderBase::BaseSerializer
-
attributes(:id, :account_id, :files, :status)
-
-
attribute :files do |object|
-
if object.files.present?
-
arr = []
-
object.files.each do |picture|
-
arr << {
-
id: picture.id,
-
file_name: picture.filename.to_s,
-
file_url: Rails.application.routes.url_helpers.rails_blob_url(picture, only_path: true)
-
}
-
end
-
arr
-
end
-
end
-
-
class << self
-
private
-
-
def attachment(object)
-
object&.attachment&.service_url if object&.attachment&.attached?
-
end
-
end
-
end
-
end
-
1
module BxBlockBulkUploading
-
1
class BundleManagementSerializer < BuilderBase::BaseSerializer
-
1
attributes :title, :total_pricing, :books_count, :board, :school_class_id
-
-
1
attributes :cover_images do |object, params|
-
-
1
if object.cover_images.attached?
-
1
host_url = params[:host] || ''
-
1
image_urls = object.cover_images.map do |image|
-
1
host_url + Rails.application.routes.url_helpers.rails_blob_url(image, only_path: true)
-
end
-
1
image_urls.join(', ')
-
else
-
''
-
end
-
end
-
end
-
end
-
1
module BxBlockBulkUploading
-
1
class EbookSerializer < BuilderBase::BaseSerializer
-
1
attributes :title, :author, :size, :pages, :edition, :publisher, :publication_date,
-
:formats_available, :language, :description, :price, :board, :school_class_id, :subject
-
-
1
attribute :images do |object, params|
-
18
if object.images.attached?
-
13
host = params[:host] || ''
-
13
object.images.map do |image|
-
13
url = host + Rails.application.routes.url_helpers.rails_blob_url(image, only_path: true)
-
13
{ url: url }
-
end
-
else
-
5
[]
-
end
-
end
-
-
1
attributes :pdf do |object, params|
-
18
if object.pdf.attached?
-
13
host = params[:host] || ''
-
13
url = host + Rails.application.routes.url_helpers.rails_blob_url(object.pdf, only_path: true)
-
else
-
5
''
-
end
-
end
-
end
-
end
-
-
1
module BxBlockCatalogue
-
1
class AssignmentSerializer < BuilderBase::BaseSerializer
-
1
attributes :id, :title, :description
-
-
1
attributes :assignment_pdf do |object|
-
4
if object.assignment.attached?
-
4
Rails.application.routes.url_helpers.rails_blob_url(object.assignment, only_path: true)
-
else
-
nil
-
end
-
end
-
-
1
attributes :teacher_name do |object|
-
4
AccountBlock::Account.find_by(id: object.account_id).first_name rescue nil
-
end
-
-
1
attributes :subject do |object|
-
4
BxBlockCatalogue::Subject.find_by(id: object.subject_id).subject_name rescue nil
-
end
-
-
1
attributes :class do |object|
-
4
BxBlockCategories::SchoolClass.find(object.school_class_id).class_number rescue nil
-
end
-
-
1
attributes :division do |object|
-
4
BxBlockCategories::ClassDivision.find(object.class_division_id).division_name rescue nil
-
end
-
end
-
end
-
module BxBlockCatalogue
-
class BrandSerializer < BuilderBase::BaseSerializer
-
attributes :id, :name, :currency, :created_at, :updated_at
-
end
-
end
-
module BxBlockCatalogue
-
class CatalogueSerializer < BuilderBase::BaseSerializer
-
attributes :sub_category, :brand, :tags, :reviews,
-
:name, :sku, :description, :manufacture_date,
-
:length, :breadth, :height, :stock_qty,
-
:availability, :weight, :price, :recommended,
-
:on_sale, :sale_price, :discount
-
-
attribute :category do |object, params|
-
object.category &&
-
BxBlockCategories::CategorySerializer.new(object.category, params: params).serializable_hash[:data]
-
end
-
-
attribute :images do |object, params|
-
host = params[:host] || ""
-
-
if object.images.attached?
-
object.images.map { |image|
-
{
-
id: image.id,
-
url: host + Rails.application.routes.url_helpers.rails_blob_url(
-
image, only_path: true
-
)
-
}
-
}
-
end
-
end
-
-
attribute :average_rating, &:average_rating
-
-
attribute :catalogue_variants do |object, params|
-
serializer = CatalogueVariantSerializer.new(
-
object.catalogue_variants, {params: params}
-
)
-
serializer.serializable_hash[:data]
-
end
-
end
-
end
-
module BxBlockCatalogue
-
class CatalogueVariantColorSerializer < BuilderBase::BaseSerializer
-
attributes :id, :name, :created_at, :updated_at
-
end
-
end
-
module BxBlockCatalogue
-
class CatalogueVariantSerializer < BuilderBase::BaseSerializer
-
attributes :id, :catalogue_id, :catalogue_variant_color_id,
-
:catalogue_variant_size_id, :price, :stock_qty, :on_sale,
-
:sale_price, :discount_price, :length, :breadth, :height,
-
:created_at, :updated_at
-
-
attribute :images do |object, params|
-
host = params[:host] || ""
-
-
if object.images.attached?
-
object.images.map { |image|
-
{
-
id: image.id,
-
url: host + Rails.application.routes.url_helpers.rails_blob_url(
-
image, only_path: true
-
)
-
}
-
}
-
end
-
end
-
end
-
end
-
module BxBlockCatalogue
-
class CatalogueVariantSizeSerializer < BuilderBase::BaseSerializer
-
attributes :id, :name, :created_at, :updated_at
-
end
-
end
-
1
module BxBlockCatalogue
-
1
class EbookAssignedSerializer < BuilderBase::BaseSerializer
-
-
1
attributes :ebook_name do |object|
-
2
object.ebook.title rescue nil
-
end
-
-
1
attributes :subject do |object|
-
2
object.ebook.subject rescue nil
-
end
-
-
1
attributes :class do |object|
-
2
BxBlockCategories::SchoolClass.find_by(id: object.school_class_id).class_number rescue nil
-
end
-
-
1
attributes :division do |object|
-
2
BxBlockCategories::ClassDivision.find_by(id: object.class_division_id).division_name rescue nil
-
end
-
end
-
end
-
module BxBlockCatalogue
-
class ErrorSerializer < BuilderBase::BaseSerializer
-
attribute :errors do |catalogue|
-
catalogue.errors.as_json
-
end
-
end
-
end
-
module BxBlockCatalogue
-
class ReviewSerializer < BuilderBase::BaseSerializer
-
attributes :id, :catalogue_id, :rating, :comment, :created_at, :updated_at
-
end
-
end
-
1
module BxBlockCatalogue
-
1
class StudentSerializer < BuilderBase::BaseSerializer
-
1
include FastJsonapi::ObjectSerializer
-
1
attributes :id, :first_name, :student_unique_id
-
-
1
attributes :class do |object|
-
3
BxBlockCategories::SchoolClass.find_by(id: object.school_class_id).class_number rescue nil
-
end
-
-
1
attributes :division do |object|
-
3
BxBlockCategories::ClassDivision.find_by(id: object.class_division_id).division_name rescue nil
-
end
-
-
1
attributes :assignment_status do |object|
-
3
object.assignment_status || false
-
end
-
-
1
attributes :video_status do |object|
-
3
object.video_status || false
-
end
-
-
1
attributes :ebook_status do |object|
-
object.ebook_status || false
-
end
-
-
1
attributes :assignment_complete do |object|
-
3
object.assignment_download || false
-
end
-
-
1
attributes :ebook_status do |object|
-
3
object.ebook_status || false
-
end
-
-
1
attributes :ebook_download do |object|
-
3
object.ebook_download || false
-
end
-
-
1
attributes :date_assigned do |object, params|
-
3
if params[:video_lecture_id].present?
-
1
BxBlockCatalogue::VideosLecture.find(params[:video_lecture_id]).created_at
-
2
elsif params[:assignment_id].present?
-
1
BxBlockCatalogue::Assignment.find(params[:assignment_id]).created_at
-
1
else params[:ebook_alloment_id]
-
1
BxBlockBulkUploading::EbookAllotment.find(params[:ebook_alloment_id]).created_at
-
end
-
end
-
end
-
end
-
module BxBlockCatalogue
-
class StudyMaterialSerializer < BuilderBase::BaseSerializer
-
-
attributes :videos do |object|
-
object.videos_lectures.map { |video|
-
BxBlockCatalogue::VideoSerializer.new(video).serializable_hash }
-
end
-
-
attributes :assignments do |object|
-
object.assignments.map { |assignment| BxBlockCatalogue::AssignmentSerializer.new(assignment).serializable_hash }
-
end
-
end
-
end
-
module BxBlockCatalogue
-
class TagSerializer < BuilderBase::BaseSerializer
-
attributes :id, :name, :created_at, :updated_at
-
end
-
end
-
1
module BxBlockCatalogue
-
1
class VideoSerializer < BuilderBase::BaseSerializer
-
1
include FastJsonapi::ObjectSerializer
-
1
attributes :id, :title, :description , :video , :time_hour, :time_min
-
-
1
attributes :teacher_name do |object|
-
4
AccountBlock::Account.find_by(id: object.account_id).first_name rescue nil
-
end
-
-
1
attributes :subject do |object|
-
4
BxBlockCatalogue::Subject.find_by(id: object.subject_id).subject_name rescue nil
-
end
-
-
1
attributes :class do |object|
-
4
BxBlockCategories::SchoolClass.find(object.school_class_id).class_number rescue nil
-
end
-
-
1
attributes :division do |object|
-
4
BxBlockCategories::ClassDivision.find(object.class_division_id).division_name rescue nil
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
module BxBlockCategories
-
class CategorySerializer < BuilderBase::BaseSerializer
-
attributes :id, :name, :dark_icon, :dark_icon_active, :dark_icon_inactive, :light_icon,
-
:light_icon_active, :light_icon_inactive, :rank, :created_at, :updated_at
-
-
attribute :sub_categories, if: proc { |_record, params|
-
params && params[:sub_categories] == true
-
}
-
-
attribute :selected_sub_categories do |object, params|
-
object.sub_categories.where(id: params[:selected_sub_categories]) if params[:selected_sub_categories].present?
-
end
-
-
attribute :light_icon do |object|
-
if object.light_icon.attached?
-
Rails.application.routes.url_helpers.rails_blob_url(object.light_icon, only_path: true)
-
end
-
end
-
-
attribute :light_icon_active do |object|
-
if object.light_icon_active.attached?
-
Rails.application.routes.url_helpers.rails_blob_url(object.light_icon_active, only_path: true)
-
end
-
end
-
-
attribute :light_icon_inactive do |object|
-
if object.light_icon_inactive.attached?
-
Rails.application.routes.url_helpers.rails_blob_url(object.light_icon_inactive, only_path: true)
-
end
-
end
-
-
attribute :dark_icon do |object|
-
if object.dark_icon.attached?
-
Rails.application.routes.url_helpers.rails_blob_url(object.dark_icon, only_path: true)
-
end
-
end
-
-
attribute :dark_icon_active do |object|
-
if object.dark_icon_active.attached?
-
Rails.application.routes.url_helpers.rails_blob_url(object.dark_icon_active, only_path: true)
-
end
-
end
-
-
attribute :dark_icon_inactive do |object|
-
if object.dark_icon_inactive.attached?
-
Rails.application.routes.url_helpers.rails_blob_url(object.dark_icon_inactive, only_path: true)
-
end
-
end
-
end
-
end
-
1
module BxBlockCategories
-
1
class ClassAllocatedSerializer < BuilderBase::BaseSerializer
-
1
attribute :class do |class_division|
-
class_division&.school_class.class_number
-
end
-
-
1
attribute :class_division do |class_division|
-
class_division&.division_name
-
end
-
-
1
attribute :department do |class_division|
-
AccountBlock::Account.find(class_division.account_id).department rescue nil
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
module BxBlockCategories
-
class CtaSerializer < BuilderBase::BaseSerializer
-
attributes :id, :headline, :description, :category_id, :is_square_cta, :is_long_rectangle_cta,
-
:is_text_cta, :is_image_cta, :has_button, :button_text, :redirect_url,
-
:visible_on_details_page, :visible_on_home_page, :text_alignment, :button_alignment,
-
:long_background_image, :square_background_image, :created_at, :updated_at
-
-
attribute :long_background_image, &:long_background_image_url
-
-
attribute :square_background_image, &:square_background_image_url
-
end
-
end
-
# frozen_string_literal: true
-
-
module BxBlockCategories
-
class ErrorSerializer < BuilderBase::BaseSerializer
-
attribute :errors do |coupon|
-
coupon.errors.as_json
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
1
module BxBlockCategories
-
1
class SchoolSerializer < BuilderBase::BaseSerializer
-
1
attributes :id, :name
-
end
-
end
-
1
module BxBlockCategories
-
1
class StudentDetailsSerializer < BuilderBase::BaseSerializer
-
1
attribute :name do |acc|
-
13
acc&.first_name
-
end
-
-
1
attribute :student_id do |acc|
-
13
acc&.student_unique_id
-
end
-
-
1
attribute :class do |acc|
-
13
acc&.class_division&.school_class&.class_number
-
end
-
-
1
attribute :division do |acc|
-
13
acc&.class_division&.division_name
-
end
-
-
# attribute :department do |acc|
-
# acc.class_division.department rescue nil
-
# end
-
end
-
end
-
# frozen_string_literal: true
-
-
module BxBlockCategories
-
class SubCategorySerializer < BuilderBase::BaseSerializer
-
attributes :id, :name, :created_at, :updated_at
-
-
attribute :categories, if: proc { |_record, params|
-
params && params[:categories] == true
-
}
-
end
-
end
-
1
module BxBlockCategories
-
1
class TeacherDetailsSerializer < BuilderBase::BaseSerializer
-
1
attribute :name do |acc|
-
acc&.first_name
-
end
-
-
1
attribute :contact_number do |acc|
-
acc&.full_phone_number
-
end
-
-
1
attribute :department do |acc|
-
acc.department rescue nil
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
module BxBlockComments
-
class CommentSerializer < BuilderBase::BaseSerializer
-
include FastJsonapi::ObjectSerializer
-
attributes(:id, :account_id, :commentable_id, :commentable_type, :comment, :created_at, :updated_at, :commentable,
-
:account)
-
end
-
end
-
module BxBlockContactUs
-
class ContactSerializer < BuilderBase::BaseSerializer
-
attributes *[
-
:name,
-
:email,
-
:phone_number,
-
:description,
-
:created_at,
-
]
-
-
attribute :account do |object|
-
AccountBlock::AccountSerializer.new(object.account)
-
end
-
-
# class << self
-
# private
-
-
# def user_for(object)
-
# "#{object.account.first_name} #{object.account.last_name}"
-
# end
-
# end
-
end
-
end
-
module BxBlockContentManagement
-
class AudioPodcastSerializer < BuilderBase::BaseSerializer
-
attributes :id, :heading, :description, :image, :audio, :created_at, :updated_at
-
attributes :image do |object|
-
object.image.image_url if object.image.present?
-
end
-
attributes :audio do |object|
-
object.audio.audio_url if object.audio.present?
-
end
-
end
-
end
-
module BxBlockContentManagement
-
class AuthorSerializer < BuilderBase::BaseSerializer
-
attributes :id, :name, :bio, :created_at, :updated_at
-
attributes :contents do |object|
-
BxBlockContentManagement::ContentSerializer.new(object.contents)
-
end
-
attributes :image do |object|
-
object.image.image_url if object.image.present?
-
end
-
end
-
end
-
module BxBlockContentManagement
-
class BookmarkSerializer < BuilderBase::BaseSerializer
-
attributes :id, :account, :content, :created_at, :updated_at
-
end
-
end
-
module BxBlockContentManagement
-
class ContentProviderSerializer < BuilderBase::BaseSerializer
-
attributes :id, :email, :partner_name, :logo, :created_at, :updated_at
-
-
attribute :follow do |object, params|
-
true if params && params[:current_user_id] && current_user_following(object, params[:current_user_id])
-
end
-
-
-
attribute :logo do |object|
-
object.logo if object.logo.present?
-
end
-
-
class << self
-
private
-
def current_user_following(record, current_user_id)
-
record.follows.where(account_id: current_user_id).present?
-
end
-
end
-
-
end
-
end
-
module BxBlockContentManagement
-
class ContentSerializer < BuilderBase::BaseSerializer
-
attributes :id, :name, :description, :image, :video, :audio, :study_material, :category,
-
:sub_category, :language, :content_type, :contentable, :feature_article,
-
:feature_video, :tag_list, :status, :publish_date, :view_count, :created_at, :updated_at
-
-
attribute :image do |object|
-
object.image if object.image.present?
-
end
-
-
attribute :video do |object|
-
object.video if object.video.present?
-
end
-
-
attribute :audio do |object|
-
object.audio if object.audio.present?
-
end
-
-
attribute :study_material do |object|
-
object.study_material if object.study_material.present?
-
end
-
-
attributes :contentable do |object|
-
case object&.content_type&.type
-
when "Live Stream"
-
BxBlockContentManagement::LiveStreamSerializer.new(object.contentable)
-
when "Videos"
-
BxBlockContentManagement::ContentVideoSerializer.new(object.contentable)
-
when "Text"
-
BxBlockContentManagement::ContentTextSerializer.new(object.contentable)
-
when "AudioPodcast"
-
BxBlockContentManagement::AudioPodcastSerializer.new(object.contentable)
-
when "Test"
-
BxBlockContentManagement::TestSerializer.new(object.contentable)
-
when "Epub"
-
BxBlockContentManagement::EpubSerializer.new(object.contentable)
-
end
-
end
-
-
class << self
-
private
-
def current_user_bookmark(record, current_user_id)
-
record.bookmarks.where(account_id: current_user_id).present?
-
end
-
end
-
end
-
end
-
module BxBlockContentManagement
-
class ContentTextSerializer < BuilderBase::BaseSerializer
-
attributes :id, :headline, :content, :images, :videos,:hyperlink, :affiliation ,:created_at, :updated_at
-
attributes :images do |object|
-
if object.images.present?
-
object.images.each do |image|
-
image.image_url if image.present?
-
end
-
else
-
[]
-
end
-
end
-
attributes :videos do |object|
-
if object.videos.present?
-
object.videos.each do |video|
-
video.video_url if video.present?
-
end
-
else
-
[]
-
end
-
end
-
end
-
end
-
module BxBlockContentManagement
-
class ContentTypeSerializer < BuilderBase::BaseSerializer
-
attributes :id, :name, :type, :identifier, :created_at, :updated_at
-
end
-
end
-
module BxBlockContentManagement
-
class ContentVideoSerializer < BuilderBase::BaseSerializer
-
attributes :id, :separate_section, :headline, :description, :thumbnails, :image, :video, :created_at, :updated_at
-
attributes :image do |object|
-
object.image.image_url if object.image.present?
-
end
-
attributes :video do |object|
-
object.video.video_url if object.video.present?
-
end
-
end
-
end
-
module BxBlockContentManagement
-
class EpubSerializer < BuilderBase::BaseSerializer
-
attributes :id, :heading, :files, :description, :created_at, :updated_at
-
attributes :files do |object|
-
if object.pdfs.present?
-
object.pdfs.each do |pdf|
-
pdf.pdf_url if pdf.present?
-
end
-
else
-
[]
-
end
-
end
-
end
-
end
-
module BxBlockContentManagement
-
class ErrorSerializer < BuilderBase::BaseSerializer
-
attribute :errors do |follow|
-
follow.errors.as_json
-
end
-
end
-
end
-
module BxBlockContentManagement
-
class ExamSerializer < BuilderBase::BaseSerializer
-
attributes :id, :heading, :description, :created_at, :updated_at
-
end
-
end
-
module BxBlockContentManagement
-
class FollowSerializer < BuilderBase::BaseSerializer
-
attributes :id, :account, :content_provider, :created_at, :updated_at
-
end
-
end
-
module BxBlockContentManagement
-
class LiveStreamSerializer < BuilderBase::BaseSerializer
-
attributes :id, :headline, :comment_section, :created_at, :updated_at
-
end
-
end
-
module BxBlockContentManagement
-
class TagSerializer < BuilderBase::BaseSerializer
-
attributes :id, :name, :taggings_count, :created_at, :updated_at
-
end
-
end
-
module BxBlockContentManagement
-
class TestSerializer < BuilderBase::BaseSerializer
-
attributes :id, :description, :created_at, :updated_at
-
end
-
end
-
module BxBlockCouponCg
-
class CouponCodeSerializer < BuilderBase::BaseSerializer
-
attributes *[
-
:id,
-
:title,
-
:description,
-
:code,
-
:discount_type,
-
:discount,
-
:valid_from,
-
:valid_to,
-
:min_cart_value,
-
:max_cart_value,
-
:created_at,
-
:updated_at
-
]
-
end
-
end
-
module BxBlockCouponCg
-
class ErrorSerializer < BuilderBase::BaseSerializer
-
attribute :errors do |coupon|
-
coupon.errors.as_json
-
end
-
end
-
end
-
module BxBlockDashboard
-
class CandidateSerializer < BuilderBase::BaseSerializer
-
-
# attribute :total_candidates do |object, params|
-
# total_candidates = params[:total_candidates]
-
# end
-
attribute :total_candidates do |object|
-
-
object.sub_attributres.map{|p| p.values.map{|p| p.to_i}}.flatten.sum
-
end
-
attribute :sub_attributres do |object|
-
object.sub_attributres
-
end
-
end
-
end
-
-
module BxBlockDashboardguests
-
class CompanySerializer < BuilderBase::BaseSerializer
-
attributes :company_name, :company_holder
-
-
attribute :doc do |object, params|
-
host = params[:host] || ''
-
url = ""
-
if object&.doc&.attached?
-
url = host + Rails.application.routes.url_helpers.rails_blob_url(
-
object.doc, only_path: true)
-
end
-
end
-
end
-
end
-
module BxBlockDashboardguests
-
class DashboardGuestSerializer < BuilderBase::BaseSerializer
-
attributes :company_id, :invest_amount, :date_of_invest
-
attribute :company_name do |guest|
-
guest.company.company_name
-
end
-
-
attribute :doc do |object, params|
-
host = params[:host] || ''
-
url = ""
-
if object&.company.doc&.attached?
-
url = host + Rails.application.routes.url_helpers.rails_blob_url(
-
object.company.doc, only_path: true)
-
end
-
end
-
end
-
end
-
module BxBlockDatastorage
-
class FileDocumentSerializer
-
include FastJsonapi::ObjectSerializer
-
-
attributes *[
-
:title,
-
:description,
-
:document_type,
-
:created_at,
-
:updated_at
-
]
-
-
attribute :attachments do |obj|
-
obj.document_file_url
-
end
-
-
attribute :account do |object|
-
object.account
-
end
-
end
-
end
-
class BxBlockDownload::DownloadablesSerializer
-
include JSONAPI::Serializer
-
attributes :id, :reference_id, :reference_type, :last_download_at
-
attribute :files do |object|
-
if object.files.count > 0
-
files = []
-
object.files.each do |file|
-
files << { id: file.id, name: file.filename, downloaded_at: file.downloaded_at }
-
end
-
files
-
end
-
end
-
end
-
1
module BxBlockElasticsearch
-
1
class AccountSerializer < BuilderBase::BaseSerializer
-
1
attribute :user_type do |acc|
-
acc&.role.name
-
end
-
-
1
attribute :name do |acc|
-
acc&.first_name
-
end
-
-
1
attribute :student_id do |acc|
-
acc&.student_unique_id
-
end
-
-
1
attribute :teacher_id do |acc|
-
acc&.teacher_unique_id
-
end
-
-
1
attribute :teacher_email do |acc|
-
acc&.email
-
end
-
-
1
attribute :phone_number do |acc|
-
acc&.full_phone_number
-
end
-
-
1
attribute :class do |acc|
-
acc&.class_division&.school_class&.class_number
-
end
-
-
1
attribute :division do |acc|
-
acc&.class_division&.division_name
-
end
-
-
1
attribute :department do |acc|
-
acc.class_division.department rescue nil
-
end
-
-
1
attribute :guardian_email do |acc|
-
acc&.guardian_email
-
end
-
-
1
attribute :guardian_name do |acc|
-
acc&.guardian_name
-
end
-
end
-
end
-
1
module BxBlockElasticsearch
-
1
class AssignmentSerializer < BuilderBase::BaseSerializer
-
1
attributes :title, :description, :school_id
-
-
# attributes :assignment_pdf do |object|
-
# if object.assignment.attached?
-
# Rails.application.routes.url_helpers.rails_blob_url(object.assignment, only_path: true)
-
# else
-
# nil
-
# end
-
# end
-
end
-
end
-
1
module BxBlockElasticsearch
-
1
class EbookSerializer < BuilderBase::BaseSerializer
-
1
attributes :title, :author, :edition, :publisher, :publication_date, :price, :board, :school_class_id, :subject
-
-
1
attribute :images do |object, params|
-
if object.images.attached?
-
host = params[:host] || ''
-
object.images.map do |image|
-
url = host + Rails.application.routes.url_helpers.rails_blob_url(image, only_path: true)
-
{ url: url }
-
end
-
else
-
[]
-
end
-
end
-
end
-
end
-
-
module BxBlockFavourites
-
class FavouriteSerializer < BuilderBase::BaseSerializer
-
attributes(:favouriteable_id, :favouriteable_type, :user_id, :created_at, :updated_at)
-
end
-
end
-
# == Schema Information
-
#
-
# Table name: arrival_windows
-
#
-
# id :bigint not null, primary key
-
# begin_at :datetime
-
# end_at :datetime
-
# exclude_begin :boolean default(TRUE)
-
# exclude_end :boolean default(TRUE)
-
# created_at :datetime not null
-
# updated_at :datetime not null
-
# addressable_id :integer
-
#
-
module BxBlockFedexIntegration
-
class ArrivalWindowSerializer < BuilderBase::BaseSerializer
-
attributes *[
-
:exclude_begin,
-
:exclude_end,
-
:begin,
-
:end,
-
]
-
-
attribute :begin do |object|
-
object.begin_at
-
end
-
-
attribute :end do |object|
-
object.end_at
-
end
-
end
-
end
-
# == Schema Information
-
#
-
# Table name: cod_values
-
#
-
# id :bigint not null, primary key
-
# shipment_id :bigint not null
-
# amount :float
-
# currency :string default("RS")
-
# created_at :datetime not null
-
# updated_at :datetime not null
-
#
-
module BxBlockFedexIntegration
-
class CodValueSerializer < BuilderBase::BaseSerializer
-
attributes *[
-
:amount,
-
:currency,
-
]
-
end
-
end
-
# == Schema Information
-
#
-
# Table name: coordinates
-
#
-
# id :bigint not null, primary key
-
# latitude :string
-
# longitude :string
-
# created_at :datetime not null
-
# updated_at :datetime not null
-
# addressable_id :integer
-
#
-
module BxBlockFedexIntegration
-
class CoordinateSerializer < BuilderBase::BaseSerializer
-
attributes *[
-
:latitude,
-
:longitude,
-
]
-
end
-
end
-
# == Schema Information
-
#
-
# Table name: create_shipments
-
#
-
# id :bigint not null, primary key
-
# auto_assign_drivers :boolean default(FALSE)
-
# requested_by :string
-
# shipper_id :string
-
# waybill :string
-
# created_at :datetime not null
-
# updated_at :datetime not null
-
#
-
module BxBlockFedexIntegration
-
class CreateShipmentSerializer < BuilderBase::BaseSerializer
-
attributes *[
-
:auto_assign_drivers,
-
:requested_by,
-
:shipper_id,
-
:shipments,
-
]
-
-
attribute :shipments do |object|
-
ShipmentSerializer
-
.new(object.shipments)
-
.serializable_hash[:data]
-
.map { |data| data[:attributes] }
-
end
-
end
-
end
-
# == Schema Information
-
#
-
# Table name: addressables
-
#
-
# id :bigint not null, primary key
-
# shipment_id :bigint not null
-
# address :text
-
# address2 :text
-
# city :string
-
# country :string
-
# email :string
-
# name :string
-
# phone :string
-
# instructions :text
-
# type :string
-
# created_at :datetime not null
-
# updated_at :datetime not null
-
#
-
module BxBlockFedexIntegration
-
class DeliverySerializer < BuilderBase::BaseSerializer
-
attributes *[
-
:address,
-
:address2,
-
:city,
-
:country,
-
:email,
-
:name,
-
:phone,
-
:instructions,
-
:arrival_window,
-
:coordinate,
-
]
-
-
attribute :arrival_window do |object|
-
ArrivalWindowSerializer
-
.new(object.arrival_window)
-
.serializable_hash[:data][:attributes]
-
end
-
-
attribute :coordinate do |object|
-
CoordinateSerializer
-
.new(object.coordinate)
-
.serializable_hash[:data][:attributes]
-
end
-
end
-
end
-
# == Schema Information
-
#
-
# Table name: dimensions
-
#
-
# id :bigint not null, primary key
-
# item_id :bigint not null
-
# height :float
-
# length :float
-
# width :float
-
# created_at :datetime not null
-
# updated_at :datetime not null
-
#
-
module BxBlockFedexIntegration
-
class DimensionSerializer < BuilderBase::BaseSerializer
-
attributes *[
-
:height,
-
:length,
-
:width,
-
]
-
end
-
end
-
# == Schema Information
-
#
-
# Table name: items
-
#
-
# id :bigint not null, primary key
-
# shipment_id :bigint not null
-
# ref_id :string
-
# weight :float
-
# quantity :integer
-
# stackable :boolean default(TRUE)
-
# item_type :integer default("PALLET")
-
# created_at :datetime not null
-
# updated_at :datetime not null
-
#
-
module BxBlockFedexIntegration
-
class ItemSerializer < BuilderBase::BaseSerializer
-
attributes *[
-
:ref_id,
-
:weight,
-
:quantity,
-
:stackable,
-
:type,
-
:dimensions,
-
]
-
-
attribute :type do |object|
-
object.item_type
-
end
-
-
attribute :dimensions do |object|
-
DimensionSerializer
-
.new(object.dimension)
-
.serializable_hash[:data][:attributes]
-
end
-
end
-
end
-
# == Schema Information
-
#
-
# Table name: addressables
-
#
-
# id :bigint not null, primary key
-
# shipment_id :bigint not null
-
# address :text
-
# address2 :text
-
# city :string
-
# country :string
-
# email :string
-
# name :string
-
# phone :string
-
# instructions :text
-
# type :string
-
# created_at :datetime not null
-
# updated_at :datetime not null
-
#
-
module BxBlockFedexIntegration
-
class PickupSerializer < BuilderBase::BaseSerializer
-
attributes *[
-
:address,
-
:address2,
-
:city,
-
:country,
-
:email,
-
:name,
-
:phone,
-
:arrival_window,
-
:coordinate,
-
]
-
-
attribute :arrival_window do |object|
-
ArrivalWindowSerializer
-
.new(object.arrival_window)
-
.serializable_hash[:data][:attributes]
-
end
-
-
attribute :coordinate do |object|
-
CoordinateSerializer
-
.new(object.coordinate)
-
.serializable_hash[:data][:attributes]
-
end
-
end
-
end
-
# == Schema Information
-
#
-
# Table name: shipments
-
#
-
# id :bigint not null, primary key
-
# create_shipment_id :bigint not null
-
# ref_id :string
-
# full_truck :boolean default(FALSE)
-
# load_description :text
-
# created_at :datetime not null
-
# updated_at :datetime not null
-
#
-
module BxBlockFedexIntegration
-
class ShipmentSerializer < BuilderBase::BaseSerializer
-
attributes *[
-
:ref_id,
-
:full_truck,
-
:load_description,
-
:cod_value,
-
:shipment_value,
-
:delivery,
-
:pickup,
-
:items,
-
]
-
-
attribute :cod_value do |object|
-
CodValueSerializer
-
.new(object.cod_value)
-
.serializable_hash[:data][:attributes]
-
end
-
-
attribute :shipment_value do |object|
-
ShipmentValueSerializer
-
.new(object.shipment_value)
-
.serializable_hash[:data][:attributes]
-
end
-
-
attribute :delivery do |object|
-
DeliverySerializer
-
.new(object.delivery)
-
.serializable_hash[:data][:attributes]
-
end
-
-
attribute :pickup do |object|
-
PickupSerializer
-
.new(object.pickup)
-
.serializable_hash[:data][:attributes]
-
end
-
-
attribute :items do |object|
-
ItemSerializer
-
.new(object.items)
-
.serializable_hash[:data]
-
.map { |data| data[:attributes] }
-
end
-
end
-
end
-
# == Schema Information
-
#
-
# Table name: shipment_values
-
#
-
# id :bigint not null, primary key
-
# shipment_id :bigint not null
-
# amount :float
-
# currency :string
-
# created_at :datetime not null
-
# updated_at :datetime not null
-
#
-
module BxBlockFedexIntegration
-
class ShipmentValueSerializer < BuilderBase::BaseSerializer
-
attributes *[
-
:amount,
-
:currency,
-
]
-
end
-
end
-
module BxBlockForgotPassword
-
class EmailOtpSerializer < BuilderBase::BaseSerializer
-
end
-
end
-
module BxBlockForgotPassword
-
class SmsOtpSerializer < BuilderBase::BaseSerializer
-
attributes :full_phone_number, :activated, :created_at
-
attributes :pin, :valid_until
-
end
-
end
-
1
module BxBlockLandingpage2
-
1
class AccountSerializer < BuilderBase::BaseSerializer
-
1
attribute :user_type do |acc|
-
4
acc&.role.name
-
end
-
-
1
attribute :name do |acc|
-
4
acc&.first_name
-
end
-
-
1
attribute :student_id do |acc|
-
4
acc&.student_unique_id
-
end
-
-
1
attribute :teacher_id do |acc|
-
4
acc&.teacher_unique_id
-
end
-
-
1
attribute :teacher_email do |acc|
-
4
acc&.email
-
end
-
-
1
attribute :phone_number do |acc|
-
4
acc&.full_phone_number
-
end
-
-
1
attribute :class do |acc|
-
4
acc&.class_division&.school_class&.class_number
-
end
-
-
1
attribute :division do |acc|
-
4
acc&.class_division&.division_name
-
end
-
-
1
attribute :department do |acc|
-
4
acc&.class_division&.department rescue nil
-
end
-
-
1
attribute :guardian_email do |acc|
-
4
acc&.guardian_email
-
end
-
-
1
attributes :subject do |object|
-
4
BxBlockCatalogue::Subject.find_by(account_id: object&.id).subject_name rescue nil
-
end
-
-
1
attribute :guardian_name do |acc|
-
4
acc&.guardian_name
-
end
-
-
1
attributes :photo do |object, params|
-
4
if object.profile&.photo&.attached?
-
host = params[:host] || ''
-
url = host + Rails.application.routes.url_helpers.rails_blob_url(object.profile.photo, only_path: true)
-
else
-
4
''
-
end
-
end
-
end
-
end
-
1
module BxBlockLandingpage2
-
1
class AssignmentSerializer < BuilderBase::BaseSerializer
-
1
attributes :id, :title
-
-
-
1
attributes :subject do |object|
-
1
BxBlockCatalogue::Subject.find_by(id: object.subject_id).subject_name rescue nil
-
end
-
-
1
attributes :downloads do |object|
-
rescue nil
-
end
-
-
1
attributes :date_assigned do |object|
-
rescue nil
-
end
-
-
1
attributes :status do |object|
-
rescue nil
-
end
-
-
1
attributes :teacher_name do |object|
-
1
AccountBlock::Account.find_by(id: object.account_id).first_name rescue nil
-
end
-
-
1
attributes :class do |object|
-
1
BxBlockCategories::SchoolClass.find(object.school_class_id).class_number rescue nil
-
end
-
-
1
attributes :division do |object|
-
1
BxBlockCategories::ClassDivision.find(object.class_division_id).division_name rescue nil
-
end
-
end
-
end
-
1
module BxBlockLandingpage2
-
1
class EbookSerializer < BuilderBase::BaseSerializer
-
# attributes :title, :author, :edition, :publisher, :publication_date, :price, :board, :school_class_id, :subject
-
-
1
attributes :ebook_name do |object|
-
4
object&.title
-
rescue nil
-
end
-
-
1
attributes :subject do |object|
-
4
object&.subject
-
rescue nil
-
end
-
-
1
attributes :downloads do |object|
-
rescue nil
-
end
-
-
1
attributes :date_assigned do |object|
-
4
object&.updated_at
-
rescue nil
-
end
-
-
1
attributes :status do |object|
-
rescue nil
-
end
-
-
1
attributes :date_downloaded do |object|
-
rescue nil
-
end
-
end
-
end
-
-
1
module BxBlockLandingpage2
-
1
class LandingpageSerializer < BuilderBase::BaseSerializer
-
1
attribute :name do |acc|
-
5
acc.try(:first_name)
-
end
-
-
1
attribute :student_id do |acc|
-
5
acc.try(:student_unique_id)
-
end
-
-
1
attribute :class do |acc|
-
5
acc&.class_division&.school_class&.class_number
-
end
-
-
1
attribute :division do |acc|
-
5
acc&.class_division&.division_name
-
end
-
-
1
attribute :department do |acc|
-
5
acc.class_division.department rescue nil
-
end
-
-
1
attribute :guardian_email do |acc|
-
5
acc.try(:guardian_email)
-
end
-
-
1
attributes :photo do |object, params|
-
5
if object.try(:profile).try(:photo).try(:attached?)
-
host_url = params[:host]
-
host_url + Rails.application.routes.url_helpers.rails_blob_url(object.try(:profile).try(:photo), only_path: true, host: host_url)
-
else
-
5
''
-
end
-
end
-
end
-
end
-
1
module BxBlockLandingpage2
-
1
class TeacherAllocatedSerializer < BuilderBase::BaseSerializer
-
-
1
attribute :teacher_id do |object|
-
object&.account.id
-
end
-
-
1
attribute :teacher_unique_id do |object|
-
object&.account.teacher_unique_id
-
end
-
-
1
attribute :name do |object|
-
object&.account.first_name
-
end
-
-
1
attributes :class do |object|
-
# object&.class_division&.school_class&.class_number
-
end
-
-
1
attributes :division do |object|
-
# BxBlockCategories::ClassDivision.find_by(id: object.class_division_id).division_name rescue nil
-
end
-
-
1
attributes :subject do |object|
-
object&.subject&.subject_name
-
end
-
end
-
end
-
1
module BxBlockLandingpage2
-
1
class TeacherAllocationSerializer < BuilderBase::BaseSerializer
-
-
1
attributes :class do |object|
-
object&.class_division&.school_class&.class_number
-
end
-
-
1
attributes :division do |object|
-
BxBlockCategories::ClassDivision.find_by(id: object.class_division_id).division_name rescue nil
-
end
-
-
1
attributes :subject do |object|
-
object&.subject&.subject_name
-
end
-
end
-
end
-
1
module BxBlockLandingpage2
-
1
class VideoSerializer < BuilderBase::BaseSerializer
-
1
include FastJsonapi::ObjectSerializer
-
1
attributes :id, :title
-
-
1
attributes :subject do |object|
-
1
BxBlockCatalogue::Subject.find_by(id: object.subject_id).subject_name rescue nil
-
end
-
-
1
attributes :date_assigned do |object|
-
rescue nil
-
end
-
-
1
attributes :status do |object|
-
rescue nil
-
end
-
end
-
end
-
module BxBlockLanguageOptions
-
class ApplicationMessageSerializer < BuilderBase::BaseSerializer
-
attributes :id, :name, :created_at, :updated_at
-
-
attribute :translations do |object|
-
TranslationSerializer.new(object.translations)
-
end
-
-
end
-
end
-
module BxBlockLanguageOptions
-
class LanguageSerializer < BuilderBase::BaseSerializer
-
attributes :id, :name, :language_code, :created_at, :updated_at
-
end
-
end
-
module BxBlockLanguageOptions
-
class TranslationSerializer < BuilderBase::BaseSerializer
-
attributes :locale, :message
-
end
-
end
-
module BxBlockLike
-
class LikeSerializer < BuilderBase::BaseSerializer
-
attributes(:likeable_id, :likeable_type, :like_by_id, :created_at, :updated_at)
-
end
-
end
-
module BxBlockLocation
-
class VanLocationSerializer < BuilderBase::BaseSerializer
-
attributes *[
-
:latitude,
-
:longitude,
-
]
-
-
attribute :van do |object|
-
object.van
-
end
-
-
attribute :service_provider do |object|
-
AccountBlock::AccountSerializer.new(object.van.service_provider)
-
end
-
-
attribute :distance do |object, params|
-
if params.present? && params[:coordinates].present?
-
van_location = [object.latitude, object.longitude]
-
find_distance_between_coordinates(params[:coordinates], van_location)
-
else
-
nil
-
end
-
end
-
-
class << self
-
def find_distance_between_coordinates start_address_coordinates, van_location
-
Geocoder::Calculations.distance_between(start_address_coordinates, van_location, units: :km)
-
end
-
end
-
end
-
end
-
module BxBlockMultipageforms2
-
class UserProfileSerializer < BuilderBase::BaseSerializer
-
attributes *[
-
:id,
-
:first_name,
-
:last_name,
-
:phone_number,
-
:email,
-
:gender,
-
:country,
-
:industry,
-
:message
-
]
-
-
-
end
-
end
-
module BxBlockNavmenu
-
class NavigationMenuSerializer < BuilderBase::BaseSerializer
-
attributes :id, :position, :items
-
end
-
end
-
# frozen_string_literal: true
-
-
module BxBlockOrderManagement
-
class AddressesSerializer < BuilderBase::BaseSerializer
-
attributes(:id, :name, :flat_no, :address, :address_type, :address_line_2, :zip_code, :phone_number, :latitude,
-
:longitude, :address_for, :is_default, :address_type, :city, :state, :country, :landmark, :created_at, :updated_at, :account)
-
-
attribute :account, if: proc { |_rec, params| params[:user].present? }
-
end
-
end
-
# rubocop:enable Layout/LineLength, Naming/VariableNumber
-
# frozen_string_literal: true
-
-
# == Schema Information
-
#
-
# Table name: delivery_address_orders
-
#
-
# id :bigint not null, primary key
-
# order_id :bigint not null
-
# delivery_address_id :bigint not null
-
# created_at :datetime not null
-
# updated_at :datetime not null
-
#
-
require_relative "addresses_serializer"
-
-
module BxBlockOrderManagement
-
class DeliveryAddressOrderSerializer < BuilderBase::BaseSerializer
-
belongs_to :delivery_address, serializer: AddressesSerializer
-
-
attributes(:id, :order_management_order_id, :delivery_address_id, :created_at, :updated_at, :delivery_address)
-
end
-
end
-
module BxBlockOrderManagement
-
class MyOrderSerializer < BuilderBase::BaseSerializer
-
attributes(
-
:id,
-
:order_number,
-
:amount,
-
:status,
-
:account_id,
-
:total_tax,
-
:created_at,
-
:updated_at,
-
:order_status_id,
-
:tax_charges,
-
:confirmed_at,
-
:cancelled_at,
-
:placed_at,
-
:order_date,
-
:total
-
)
-
-
attribute :order_items do |object, params|
-
if object.present?
-
OrderItemSerializer.new(
-
object.order_items, {params: params}
-
).serializable_hash[:data]
-
end
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
# == Schema Information
-
#
-
# Table name: order_items
-
#
-
# id :bigint not null, primary key
-
# order_id :bigint not null
-
# quantity :integer
-
# unit_price :decimal(, )
-
# total_price :decimal(, )
-
# old_unit_price :decimal(, )
-
# status :string
-
# created_at :datetime not null
-
# updated_at :datetime not null
-
# catalogue_id :bigint not null
-
# catalogue_variant_id :bigint not null
-
# order_status_id :integer
-
# placed_at :datetime
-
# confirmed_at :datetime
-
# in_transit_at :datetime
-
# delivered_at :datetime
-
# cancelled_at :datetime
-
# refunded_at :datetime
-
# manage_placed_status :boolean default(FALSE)
-
# manage_cancelled_status :boolean default(FALSE)
-
#
-
1
module BxBlockOrderManagement
-
1
class OrderItemSerializer < BuilderBase::BaseSerializer
-
1
attributes(:id, :order_management_order_id, :quantity, :unit_price, :total_price, :old_unit_price, :status,
-
:order_status_id, :placed_at, :confirmed_at, :created_at, :updated_at)#, :in_transit_at, :delivered_at, :cancelled_at, :refunded_at, :manage_placed_status, :manage_cancelled_status,:catalogue_id, :catalogue_variant_id)
-
-
9
attribute :order, if: proc { |_rec, params| params[:order].present? }
-
1
attribute :order_statuses do |object, params|
-
8
if params.present?
-
8
order = object.order
-
{
-
8
order_number: order.order_number,
-
placed_at: order.placed_at,
-
confirmed_at: order.confirmed_at,
-
in_transit_at: order.in_transit_at,
-
delivered_at: order.delivered_at,
-
cancelled_at: order.cancelled_at,
-
refunded_at: order.refunded_at
-
}
-
end
-
end
-
-
# attribute :ebook do |object, params|
-
# if object.present?
-
# BxBlockBulkUploading::EbookSerializer.new(
-
# object.ebook, {params: params}
-
# ).serializable_hash[:data]
-
# end
-
# end
-
end
-
end
-
# rubocop:enable Layout/LineLength
-
# frozen_string_literal: true
-
-
# == Schema Information
-
#
-
# Table name: orders
-
#
-
# id :bigint not null, primary key
-
# order_number :string
-
# amount :float
-
# created_at :datetime not null
-
# updated_at :datetime not null
-
# account_id :bigint
-
# coupon_code_id :bigint
-
# delivery_address_id :bigint
-
# sub_total :decimal(, ) default(0.0)
-
# total :decimal(, ) default(0.0)
-
# status :string
-
# applied_discount :decimal(, ) default(0.0)
-
# cancellation_reason :text
-
# order_date :datetime
-
# is_gift :boolean default(FALSE)
-
# placed_at :datetime
-
# confirmed_at :datetime
-
# in_transit_at :datetime
-
# delivered_at :datetime
-
# cancelled_at :datetime
-
# refunded_at :datetime
-
# source :string
-
# shipment_id :string
-
# delivery_charges :string
-
# tracking_url :string
-
# schedule_time :datetime
-
# payment_failed_at :datetime
-
# returned_at :datetime
-
# tax_charges :decimal(, ) default(0.0)
-
# deliver_by :integer
-
# tracking_number :string
-
# is_error :boolean default(FALSE)
-
# delivery_error_message :string
-
# payment_pending_at :datetime
-
# order_status_id :integer
-
# is_group :boolean default(TRUE)
-
# is_availability_checked :boolean default(FALSE)
-
# shipping_charge :decimal(, )
-
# shipping_discount :decimal(, )
-
# shipping_net_amt :decimal(, )
-
# shipping_total :decimal(, )
-
# total_tax :float
-
#
-
1
module BxBlockOrderManagement
-
1
class OrderSerializer < BuilderBase::BaseSerializer
-
1
attributes(:id, :order_number, :amount, :status , :account_id, :total_tax, :created_at, :updated_at, :order_status_id, :tax_charges, :confirmed_at, :cancelled_at, :placed_at, :order_date, :total)#, :coupon_code_id, :delivery_address_id, :sub_total, :custom_label, :applied_discount, :cancellation_reason, :is_gift, :in_transit_at, :delivered_at, :refunded_at, :source, :shipment_id, :delivery_charges, :tracking_url, :schedule_time, :payment_failed_at, :payment_pending_at, :returned_at, :deliver_by, :tracking_number, :is_error, :delivery_error_message, :is_group, :is_availability_checked, :shipping_charge, :shipping_discount, :shipping_net_amt, :shipping_total, :delivery_addresses, :razorpay_order_id, :charged, :invoice_id, :invoiced)
-
-
1
attribute :order_items do |object, params|
-
5
if object.present?
-
5
OrderItemSerializer.new(
-
object.order_items, {params: params}
-
).serializable_hash[:data]
-
end
-
end
-
-
# attribute :account do |object|
-
# AccountBlock::AccountSerializer.new(object.account).serializable_hash[:data] if object.present?
-
# end
-
end
-
end
-
# rubocop:enable Layout/LineLength
-
module BxBlockPosts
-
class ErrorSerializer < BuilderBase::BaseSerializer
-
attribute :errors do |post|
-
post.errors.as_json
-
end
-
end
-
end
-
module BxBlockPosts
-
class PostSerializer < BuilderBase::BaseSerializer
-
-
attributes *[
-
:id,
-
:name,
-
:description,
-
:body,
-
:location,
-
:account_id,
-
:category_id,
-
:sub_category_id,
-
:created_at,
-
:updated_at
-
]
-
-
attribute :model_name do |object|
-
object.class.name
-
end
-
-
attribute :images_and_videos do |object, params|
-
host = params[:host] || ""
-
object.images.attached? ?
-
object.images.map { |image|
-
{
-
id: image.id,
-
url: host + Rails.application.routes.url_helpers.rails_blob_url(
-
image, only_path: true,
-
type: image.blob.content_type.split('/')[0]
-
)
-
}
-
} : []
-
end
-
-
attribute :media do |object, params|
-
host = params[:host] || ""
-
object.media.attached? ?
-
object.media.map { |media|
-
{
-
id: media.id,
-
url: host + Rails.application.routes.url_helpers.rails_blob_url(
-
media, only_path: true,
-
),
-
filename: media.blob[:filename],
-
content_type: media.blob[:content_type],
-
}
-
} : []
-
end
-
-
attribute :created_at do |object|
-
"#{time_ago_in_words(object.created_at)} ago"
-
end
-
end
-
end
-
module BxBlockProfile
-
class AwardSerializer < BuilderBase::BaseSerializer
-
attributes *[
-
:title,
-
:associated_with,
-
:issuer,
-
:issue_date,
-
:description,
-
:make_public
-
]
-
end
-
end
-
module BxBlockProfile
-
class CareerExperienceSerializer < BuilderBase::BaseSerializer
-
attributes *[
-
:id,
-
:job_title,
-
:start_date,
-
:end_date,
-
:company_name,
-
:description,
-
:add_key_achievements,
-
:make_key_achievements_public,
-
:profile_id,
-
:current_salary,
-
:currently_working_here,
-
:notice_period,
-
:notice_period_end_date
-
]
-
-
attributes :career_experience_industrys do |object|
-
object.career_experience_industrys.map do |car_ind|
-
{
-
id: car_ind.industry.id,
-
industry_name: car_ind.industry.industry_name
-
}
-
end
-
end
-
-
attributes :career_experience_employment_types do |object|
-
object.career_experience_employment_types.map do |car_emp|
-
{
-
id:car_emp.employment_type.id,
-
employment_type_name: car_emp.employment_type.employment_type_name
-
}
-
end
-
end
-
-
attributes :career_experience_system_experiences do |object|
-
object.career_experience_system_experiences.map do |car_exp|
-
{
-
id:car_exp.system_experience.id,
-
system_experience: car_exp.system_experience.system_experience
-
}
-
end
-
end
-
-
end
-
end
-
module BxBlockProfile
-
class CourseSerializer < BuilderBase::BaseSerializer
-
attributes *[
-
:course_name,
-
:duration,
-
:year
-
]
-
end
-
end
-
module BxBlockProfile
-
class CurrentStatusSerializer < BuilderBase::BaseSerializer
-
attributes *[
-
:most_recent_job_title,
-
:company_name,
-
:notice_period,
-
:end_date,
-
:profile_id
-
]
-
-
attributes :current_status_industrys do |object|
-
object.current_status_industrys.map do |cur_ind|
-
{
-
id: cur_ind.industry.id,
-
industry_name: cur_ind.industry.industry_name
-
}
-
end
-
end
-
-
attributes :current_status_employment_types do |object|
-
object.current_status_employment_types.map do |cur_emp|
-
{
-
id:cur_emp.employment_type.id,
-
employment_type_name: cur_emp.employment_type.employment_type_name
-
}
-
end
-
end
-
-
attributes :current_annual_salary_current_status do |object|
-
object.current_annual_salary_current_status.map do |sal_stat|
-
{
-
id:sal_stat.current_annual_salary.id,
-
employment_type_name: sal_stat.current_annual_salary.current_annual_salary
-
}
-
end
-
end
-
-
end
-
end
-
module BxBlockProfile
-
class DegreeSerializer < BuilderBase::BaseSerializer
-
attributes *[
-
:id,
-
:degree_name
-
]
-
end
-
end
-
module BxBlockProfile
-
class EducationalQualificationSerializer < BuilderBase::BaseSerializer
-
attributes *[
-
:id,
-
:school_name,
-
:start_date,
-
:end_date,
-
:grades,
-
:description,
-
:make_grades_public,
-
:profile_id
-
]
-
attributes :educational_qualification_field_studys do |object|
-
object.educational_qualification_field_studys.map do |edu_qual|
-
{
-
id: edu_qual.field_study.id,
-
field_of_study: edu_qual.field_study.field_of_study
-
}
-
end
-
end
-
-
attributes :degree_educational_qualifications do |object|
-
object.degree_educational_qualifications.map do |deg_qual|
-
{
-
id:deg_qual.degree.id,
-
degree_name: deg_qual.degree.degree_name
-
}
-
end
-
end
-
end
-
end
-
module BxBlockProfile
-
class HobbySerializer < BuilderBase::BaseSerializer
-
attributes *[
-
:title,
-
:category,
-
:description,
-
:make_public
-
]
-
end
-
end
-
module BxBlockProfile
-
class IndustrySerializer < BuilderBase::BaseSerializer
-
attributes *[
-
:id,
-
:industry_name
-
]
-
end
-
end
-
module BxBlockProfile
-
class LanguageSerializer < BuilderBase::BaseSerializer
-
attributes *[
-
:id,
-
:language,
-
:proficiency,
-
:profile_id
-
]
-
end
-
end
-
1
module BxBlockProfile
-
1
class ProfileSerializer < BuilderBase::BaseSerializer
-
1
attributes(:email, :full_phone_number, :role, :name, :school_name,
-
:publication_house_name, :guardian_email, :guardian_name,
-
:guardian_contact_no, :teacher_unique_id, :student_unique_id)
-
1
attribute :role do |object|
-
8
object.account.role&.name rescue nil
-
end
-
-
1
attribute :name do |object|
-
8
object.user_name rescue nil
-
end
-
-
1
attribute :school_name do |object|
-
8
object.account.school&.name rescue nil
-
end
-
-
1
attribute :student_details do |object|
-
8
BxBlockProfile::StudentProfileSerializer.new(object)
-
end
-
-
1
attribute :class_teacher do |object|
-
8
teacher = AccountBlock::Account.find_by_id(object.account.class_division.account_id) rescue nil
-
8
BxBlockProfile::TeacherProfileSerializer.new(teacher)
-
end
-
-
1
attribute :allocated_class do |object|
-
8
class_division = BxBlockCategories::ClassDivision.where(account_id: object.account_id)
-
8
BxBlockCategories::ClassAllocatedSerializer.new(class_division)
-
end
-
-
1
attributes :photo do |object|
-
if object.photo.attached?
-
host_url = Rails.application.routes.default_url_options[:host]
-
Rails.application.routes.url_helpers.rails_blob_url(object.photo, only_path: true, host: host_url)
-
else
-
''
-
end
-
end
-
-
1
attributes :photo do |object, params|
-
8
if object.photo.attached?
-
# host_url = Rails.application.routes.default_url_options[:host]
-
8
host = params[:host] || ''
-
8
url = host + Rails.application.routes.url_helpers.rails_blob_url(object.photo, only_path: true)
-
else
-
''
-
end
-
end
-
end
-
end
-
module BxBlockProfile
-
class ProjectSerializer < BuilderBase::BaseSerializer
-
attributes *[
-
:id,
-
:project_name,
-
:start_date,
-
:end_date,
-
:add_members,
-
:url,
-
:description,
-
:make_projects_public,
-
:profile_id
-
]
-
-
attributes :associated_projects do |object|
-
object.associated_projects.map do |ass_pro|
-
{
-
id: ass_pro.associated.id,
-
associated_with_name: ass_pro.associated.associated_with_name
-
}
-
end
-
end
-
-
end
-
end
-
module BxBlockProfile
-
class PublicationPatentSerializer < BuilderBase::BaseSerializer
-
attributes *[
-
:title,
-
:publication,
-
:authors,
-
:url,
-
:description,
-
:make_public,
-
:profile_id
-
]
-
end
-
end
-
module BxBlockProfile
-
class PublisherProfileSerializer < BuilderBase::BaseSerializer
-
attributes *[
-
:id,
-
:email,
-
:country,
-
:address,
-
:account_id,
-
:user_name,
-
:school_id,
-
:employee_unique_id,
-
:full_phone_number,
-
# :photo
-
]
-
end
-
end
-
module BxBlockProfile
-
class SchoolAdminProfileSerializer < BuilderBase::BaseSerializer
-
attributes *[
-
:id,
-
:email,
-
:country,
-
:address,
-
:account_id,
-
:school_id,
-
:user_name,
-
:full_phone_number,
-
# :photo
-
]
-
end
-
end
-
1
module BxBlockProfile
-
1
class StudentProfileSerializer < BuilderBase::BaseSerializer
-
-
1
attribute :account_id do |object|
-
8
object.account_id
-
end
-
-
1
attribute :class do |object|
-
8
BxBlockCategories::SchoolClass.find_by_id(object.account.school_class_id).class_number rescue nil
-
end
-
-
1
attribute :division do |object|
-
8
AccountBlock::Account.find(object.account_id).class_division.division_name rescue nil
-
end
-
-
# attribute :department do |object|
-
# AccountBlock::Account.find(object.account_id).class_division.department rescue nil
-
# end
-
end
-
end
-
1
module BxBlockProfile
-
1
class TeacherProfileSerializer < BuilderBase::BaseSerializer
-
1
attribute :name do |object|
-
object&.first_name
-
end
-
-
1
attribute :contact_number do |object|
-
object.full_phone_number
-
end
-
-
1
attribute :email do |object|
-
object.email
-
end
-
-
1
attribute :department do |object|
-
object.department rescue nil
-
end
-
end
-
end
-
module BxBlockProfile
-
class TestScoreAndCourseSerializer < BuilderBase::BaseSerializer
-
attributes *[
-
:title,
-
:associated_with,
-
:score,
-
:test_date,
-
:description,
-
:make_public
-
]
-
end
-
end
-
# frozen_string_literal: true
-
-
module BxBlockProfileBio
-
# achiveemnt serializer
-
class AchievementSerializer < BuilderBase::BaseSerializer
-
attributes(:title, :achievement_date, :detail, :url, :profile_bio_id, :created_at, :updated_at)
-
end
-
end
-
# frozen_string_literal: true
-
-
# profile serializer
-
module BxBlockProfileBio
-
# BxBlockProfileBio module
-
# rubocop:disable Metrics/BlockLength, Metrics/ClassLength
-
class BasicProfileSerializer < BuilderBase::BaseSerializer
-
attributes(:age, :gender, :created_at, :updated_at)
-
-
attribute :account_id, &:id
-
-
attribute :model_name do |_object|
-
'AccountBlock::Account'
-
end
-
-
attribute :full_name do |object|
-
full_name_for object
-
end
-
-
attribute :address do |object|
-
address_for object
-
end
-
-
attribute :about_me do |object|
-
object&.profile_bio&.about_me
-
end
-
-
attribute :personality do |object|
-
object&.profile_bio&.personality
-
end
-
-
attribute :interests do |object|
-
object&.profile_bio&.interests
-
end
-
-
attribute :looking_for do |object|
-
object.categories&.map(&:name)
-
end
-
-
attribute :distance_away_from do |object|
-
distance_for object
-
end
-
-
attribute :is_liked do |object|
-
like_profile_for object
-
end
-
-
attribute :is_online, &:online?
-
-
attribute :is_favourite do |object|
-
favourite_profile_for object
-
end
-
-
attribute :request_status do |object, params|
-
request = begin
-
object.recevied_requests.where(sender_id: params[:current_user_id]).first
-
rescue StandardError
-
nil
-
end
-
status = if request.blank?
-
'Not send the request'
-
elsif request.present?
-
request.status.nil? ? 'Pending' : request.status
-
else
-
'Not send the request'
-
end
-
status
-
end
-
-
attribute :about_business, if: proc { |object|
-
object.categories.map(&:name).include?('business')
-
} do |object|
-
object&.profile_bio&.about_business
-
end
-
-
attribute :custom_attributes do |object|
-
object&.profile_bio&.custom_attributes
-
end
-
-
attribute :educations, if: proc { |object|
-
object.categories.map(&:name).include?('business') ||
-
object.categories.map(&:name).include?('match_making')
-
} do |object|
-
object&.profile_bio&.educations
-
end
-
-
attribute :careers, if: proc { |object|
-
object.categories.map(&:name).include?('business') ||
-
object.categories.map(&:name).include?('match_making')
-
} do |object|
-
object&.profile_bio&.careers
-
end
-
-
attribute :achievements, if: proc { |object| object.categories.map(&:name).include?('business') } do |object|
-
object&.profile_bio&.achievements
-
end
-
-
attribute :basic_details do |object|
-
{
-
date_of_birth: object&.date_of_birth,
-
height: object&.profile_bio&.height,
-
weight: object&.profile_bio&.weight,
-
height_type: object&.profile_bio&.height_type,
-
weight_type: object&.profile_bio&.weight_type,
-
body_type: object&.profile_bio&.body_type,
-
mother_tougue: object&.profile_bio&.mother_tougue,
-
religion: object&.profile_bio&.religion,
-
zodiac: object&.profile_bio&.zodiac,
-
marital_status: object&.profile_bio&.marital_status,
-
languages: object&.profile_bio&.languages,
-
smoking: object&.profile_bio&.smoking,
-
drinking: object&.profile_bio&.drinking
-
}
-
end
-
-
attribute :images do |object|
-
image_arr = []
-
if object.images.attached?
-
object.images.each do |img|
-
image_hash = {
-
id: img.id,
-
url: Rails.application.routes.url_helpers.url_for(img)
-
}
-
image_arr << image_hash
-
end
-
end
-
image_arr
-
end
-
-
attribute :friends_list do |object, params|
-
sender_friends = BxBlockRequestManagement::Request.where(
-
'(sender_id=? or account_id=?) and status=?', object.id, object.id, 0
-
)
-
.pluck(:account_id, :sender_id)
-
receiver_friends = BxBlockRequestManagement::Request.where(
-
'(sender_id=? or account_id=?) and status=?',
-
params[:current_user_id], params[:current_user_id], 0
-
)
-
.pluck(:account_id, :sender_id)
-
-
sender_friends = sender_friends.flatten.uniq - [object.id]
-
receiver_friends = receiver_friends.flatten.uniq - [params[:current_user_id].to_i]
-
mutual_friend_ids = begin
-
sender_friends & receiver_friends
-
rescue StandardError
-
0
-
end
-
-
friends_account = AccountBlock::Account.where(id: sender_friends)
-
friends_list_arr = []
-
if friends_account.present?
-
friends_account.each do |friend_account|
-
next unless friend_account.images.attached?
-
-
img = friend_account.images.find_by(default_image: true)
-
next if img.blank?
-
-
image_hash = {
-
id: img.id,
-
record_type: img.record_type,
-
record_id: img.record_id,
-
url: Rails.application.routes.url_helpers.url_for(img),
-
default_image: img.default_image
-
}
-
-
friends_list_arr << image_hash
-
end
-
end
-
{ mutual_friends_count: mutual_friend_ids.count || 0, friends: friends_list_arr }
-
end
-
-
class << self
-
private
-
-
def like_profile_for(object)
-
object.is_liked
-
end
-
-
def favourite_profile_for(object)
-
object.is_favourite
-
end
-
-
def full_name_for(object)
-
[object&.first_name, object&.last_name].join(' ')
-
end
-
-
def address_for(object)
-
return nil if object.location.blank?
-
-
object.location&.address
-
end
-
-
def distance_for(object)
-
"#{object.distance_away || 0.0} km away"
-
end
-
end
-
end
-
# rubocop:enable Metrics/BlockLength,Metrics/ClassLength
-
end
-
# frozen_string_literal: true
-
-
module BxBlockProfileBio
-
# carrer serializer
-
class CareerSerializer < BuilderBase::BaseSerializer
-
attributes(:profession, :is_current, :payscale, :company_name, :accomplishment, :sector, :profile_bio_id,
-
:created_at, :updated_at)
-
-
attribute :career_from_to_end do |object|
-
[object.experience_from, object.experience_to].join('-')
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
module BxBlockProfileBio
-
# education serializer
-
# BxBlockProfileBio module
-
class EducationSerializer < BuilderBase::BaseSerializer
-
attributes(:qualification, :profile_bio_id, :description, :created_at, :updated_at)
-
-
attribute :education_from_to_end do |object|
-
[object.year_from, object.year_to].join('-')
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
module BxBlockProfileBio
-
# preference serializer
-
class PreferenceSerializer < BuilderBase::BaseSerializer
-
attributes(:account_id, :seeking, :location, :distance, :age_range_start,
-
:age_range_end, :height_range_start, :height_range_end, :height_type,
-
:body_type, :religion, :smoking, :drinking, :friend, :business,
-
:match_making, :travel_partner, :cross_path, :created_at, :updated_at)
-
end
-
end
-
module BxBlockProfileBio
-
# profile bio serializer
-
class ProfileBioSerializer < BuilderBase::BaseSerializer
-
attributes(:account_id, :height, :weight, :height_type, :weight_type, :body_type, :mother_tougue,
-
:religion, :zodiac, :marital_status, :languages, :about_me, :personality, :interests, :smoking,
-
:drinking, :custom_attributes, :looking_for,
-
:created_at, :updated_at, :educations, :achievements, :careers, :account)
-
end
-
end
-
# frozen_string_literal: true
-
-
module BxBlockProfileBio
-
# view profile serializer
-
class ViewProfileSerializer < BuilderBase::BaseSerializer
-
attributes(:account_id, :view_by_id, :created_at, :updated_at)
-
-
attribute :full_name do |object|
-
[object.viewer&.first_name, object.viewer&.last_name].join(' ')
-
end
-
-
attribute :profile_image do |object|
-
image_hash = {}
-
if object.viewer.images.attached?
-
img = object.viewer.images.find_by(default_image: true)
-
if img.present?
-
image_hash = {
-
id: img.id,
-
url: Rails.application.routes.url_helpers.url_for(img),
-
default_image: img.default_image
-
}
-
end
-
end
-
image_hash
-
end
-
-
attribute :mutual_friends_count do |object|
-
object.mutual_friends&.count
-
end
-
end
-
end
-
module BxBlockPushNotifications
-
class PushNotificationSerializer < BuilderBase::BaseSerializer
-
attributes *[
-
:push_notificable_id,
-
:push_notificable_type,
-
:remarks,
-
:is_read,
-
:created_at,
-
:updated_at
-
]
-
-
attribute :account do |object|
-
AccountBlock::SmsAccountSerializer.new(object.account)
-
end
-
-
attribute :looking_for do |object|
-
object.account&.categories&.map(&:name)
-
end
-
-
attribute :profile_image do |object, params|
-
image_hash = {}
-
img = nil
-
img = object.account.images.find_by(default_image: true) if object.account.images.attached?
-
image_hash = {
-
id: img.id,
-
url: Rails.application.routes.url_helpers.url_for(img),
-
default_image: img.default_image
-
} if img.present?
-
image_hash
-
end
-
end
-
end
-
module BxBlockRequestManagement
-
class RequestSerializer < BuilderBase::BaseSerializer
-
attributes(:sender_id, :status, :rejection_reason, :request_text, :created_at, :updated_at)
-
-
attribute :reviewer_group_id do |object|
-
object.account_group_id
-
end
-
-
attribute :sender_full_name do |object|
-
[object.sender&.first_name, object.sender&.last_name].join(" ")
-
end
-
end
-
end
-
module BxBlockSettings
-
class SettingSerializer < BuilderBase::BaseSerializer
-
attributes *[
-
:name,
-
:title
-
]
-
end
-
end
-
module BxBlockShoppingCart
-
class OrderItemSerializer < BuilderBase::BaseSerializer
-
attributes(:price, :quantity, :taxable, :taxable_value, :other_charges)
-
-
attribute :catalogue do |object|
-
BxBlockCatalogue::CatalogueSerializer.new(object.catalogue)
-
end
-
end
-
end
-
module BxBlockShoppingCart
-
class OrderSerializer < BuilderBase::BaseSerializer
-
attributes(:status, :total_fees, :total_items, :total_tax)
-
-
attribute :customer do |object|
-
AccountBlock::AccountSerializer.new(object.customer)
-
end
-
-
attribute :address do |object|
-
BxBlockAddress::AddressSerializer.new(object.address)
-
end
-
-
attribute :order_items do |object|
-
BxBlockShoppingCart::OrderItemSerializer.new(object.order_items)
-
end
-
-
class << self
-
def order_services_for order
-
order.sub_categories.pluck(:name)
-
# order.services.map{|service| service.sub_category.name }
-
end
-
end
-
end
-
end
-
module BxBlockStripeIntegration
-
class PaymentIntentSerializer
-
include FastJsonapi::ObjectSerializer
-
-
attributes(:id, :amount, :amount_capturable, :amount_details, :amount_received, :charges, :client_secret, :confirmation_method, :created, :currency, :customer, :payment_method, :payment_method_types)
-
end
-
end
-
module BxBlockStripeIntegration
-
class PaymentMethodSerializer
-
include FastJsonapi::ObjectSerializer
-
-
attributes(:billing_details, :card, :customer, :created)
-
end
-
end
-
1
module BxBlockTermsAndConditions
-
1
class TermsAndConditionsSerializer < BuilderBase::BaseSerializer
-
1
attributes(:id, :description, :created_at)
-
-
1
attributes :accepted_by do |object|
-
1
arr = []
-
1
user_terms_data = object.get_accepted_accounts
-
-
1
user_terms_data.each do |user_terms|
-
arr << {
-
account_id: user_terms["account_id"],
-
accepted_on: user_terms["updated_at"],
-
email: user_terms["email"]
-
}
-
end
-
1
arr || []
-
end
-
end
-
end
-
module AccountBlock
-
class EmailValidation
-
include ActiveModel::Validations
-
-
attr_reader :email
-
-
class << self
-
def regex
-
/[^@]+@\S+[.]\S+/
-
end
-
-
def regex_string
-
regex.to_s.sub("(?-mix:", "").delete_suffix(")")
-
end
-
end
-
-
validates :email, format: {
-
with: regex,
-
multiline: true
-
}
-
-
def initialize(email)
-
@email = email
-
end
-
end
-
end
-
module AccountBlock
-
class PasswordValidation
-
include ActiveModel::Validations
-
-
attr_reader :password
-
-
class << self
-
def regex
-
# ^ Start anchor
-
# (?=.*[A-Z]) Has one uppercase letter
-
# (?=.*[!@#$&*?<>',\[\]}{=\-)(^%`~+.:;_]) Has one special case symbol
-
# (?=.*[0-9]) Has one digit
-
# (?=.*[a-z]) Has one lowercase letter
-
# .{8,} Is at least length 8
-
# $ End anchor
-
/^(?=.*[A-Z])(?=.*[#!@$&*?<>',\[\]}{=\-)(^%`~+.:;_])(?=.*[0-9])(?=.*[a-z]).{8,}$/
-
end
-
-
def regex_string
-
regex.to_s.sub("(?-mix:", "").delete_suffix(")")
-
end
-
-
def rules
-
"Password should be a minimum of 8 characters long," \
-
" contain both uppercase and lowercase characters, at" \
-
" least one digit, and one special character " \
-
'(!@#$&*?<>\',[]}{=-)(^%`~+.:;_).'
-
end
-
end
-
-
validates :password, format: {
-
with: regex,
-
multiline: true
-
}
-
-
def initialize(password)
-
@password = password
-
end
-
end
-
end
-
module AccountBlock
-
class PhoneValidation
-
include ActiveModel::Validations
-
-
attr_accessor :phone
-
-
validate :validate_phone
-
-
def initialize(phone)
-
@phone = phone
-
end
-
-
private
-
-
def validate_phone
-
return if Phonelib.valid?(@phone)
-
errors.add :phone_number, "is not valid"
-
end
-
end
-
end
-
1
module BuilderJsonWebToken
-
1
class JsonWebToken
-
1
attr_reader :id, :expiration
-
-
1
class << self
-
1
def encode(id, data = {}, expiration = nil)
-
1064
expiration, data = data, expiration unless data.is_a?(Hash)
-
-
1064
data ||= {}
-
1064
expiration ||= 24.hours.from_now
-
-
1064
payload = build_payload_for(id.to_i, data, expiration.to_i)
-
-
1064
JWT.encode payload, secret_key, algorithm
-
end
-
-
1
def decode(token)
-
141
JsonWebToken.new token_data_for(token)
-
end
-
-
1
private
-
-
1
def token_data_for(token)
-
141
JWT.decode(token, secret_key, true, {
-
:algorithm => algorithm,
-
})[0]
-
end
-
-
1
def build_payload_for(id, data, expiration)
-
{
-
1064
:id => id,
-
:exp => expiration,
-
}.merge(data)
-
end
-
-
1
def secret_key
-
1205
@secret_key ||= Rails.application.secret_key_base
-
end
-
-
1
def algorithm
-
1205
'HS512'
-
end
-
end
-
-
1
def initialize(data)
-
141
@id = data.delete('id')
-
141
@expiration = Time.at(data.delete('exp')).to_time
-
141
@struct = nil
-
141
initialize_attributes_for data if data.is_a?(Hash) && data.keys.any?
-
end
-
-
1
private
-
-
1
def initialize_attributes_for(data)
-
@struct = Struct.new(*data.keys.map(&:to_sym)).new
-
data.keys.each do |key|
-
@struct.send("#{key}=", data[key])
-
end
-
end
-
-
1
def respond_to_missing?(method, *args)
-
super || @struct.respond_to?(method)
-
end
-
-
1
def method_missing(method, *args, &block)
-
return @struct.send(method) if @struct.respond_to?(method)
-
super
-
end
-
end
-
end
-
module BxBlockAppointmentManagement
-
class TimeSlotsCalculator
-
def calculate_time_slots(start_time, end_time, slot_duration)
-
total_working_hours = (Time.parse(end_time).strftime("%H").to_i -
-
Time.parse(start_time).strftime("%H").to_i)
-
total_working_minutes = total_working_hours * 60
-
new_time_slots = []
-
new_start_time = start_time
-
sno = 1
-
until total_working_minutes < 1
-
start_time_key = Time.parse(new_start_time).strftime("%I:%M %p").to_s
-
end_time_key = (Time.parse(new_start_time) + slot_duration.minute).strftime("%I:%M %p").to_s
-
new_time_slots << {
-
from: start_time_key, to: end_time_key, booked_status: false, sno: sno.to_s
-
}
-
new_start_time = (Time.parse(new_start_time) +
-
(slot_duration + 1).minute).strftime("%I:%M %p")
-
total_working_minutes -= slot_duration
-
sno += 1
-
end
-
new_time_slots
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
module BxBlockCategories
-
class BuildCategories
-
class << self
-
CATEGORIES_AND_SUB_CATEGORIES_HASH = {
-
"K12" => [
-
"Pre Primary (kg)",
-
"Primary (1 to 5)",
-
"Middle (6 to 8)",
-
"Secondary (9 & 10)",
-
"Senior Secondary (11 & 12)"
-
],
-
"Higher Education" => [
-
"Accounting & Commerce",
-
"Animation",
-
"Architecture & Alanning",
-
"Arts (Fine/Visual/Performing)",
-
"Aviation",
-
"Banking, Finance & Insurance",
-
"Beauty & Fitness",
-
"Business & Management Studies",
-
"Design",
-
"Engineering",
-
"Hospitality & Travel",
-
"Humanities & Social Sciences",
-
"IT & Software",
-
"Law",
-
"Mass Communication & Media",
-
"Medicine & Health Sciences",
-
"Nursing",
-
"Science",
-
"Teaching & Education"
-
],
-
"Govt Job" => [
-
"Banking",
-
"Railways",
-
"Defense",
-
"Police",
-
"UGC NET",
-
"Teaching",
-
"SSC",
-
"UPSC",
-
"State PSCs",
-
"Judiciary"
-
],
-
"Competitive Exams" => %w[
-
JEE
-
NEET
-
CLAT
-
],
-
"Upskilling" => []
-
}.freeze
-
-
def call(categories_and_sub_categories = CATEGORIES_AND_SUB_CATEGORIES_HASH)
-
categories_and_sub_categories.each do |key, value|
-
category = BxBlockCategories::Category.where(
-
"lower(name) = ?", key.downcase
-
).first_or_create(name: key, identifier: category_identifier_hash[key])
-
category.update(identifier: category_identifier_hash[key])
-
value.each do |val|
-
category.sub_categories.where(
-
"lower(name) = ?", val.downcase
-
).first_or_create(name: val, categories: [category])
-
end
-
end
-
end
-
-
private
-
-
def category_identifier_hash
-
{
-
"K12" => "k12",
-
"Higher Education" => "higher_education",
-
"Govt Job" => "govt_job",
-
"Competitive Exams" => "competitive_exams",
-
"Upskilling" => "upskilling"
-
}
-
end
-
end
-
end
-
end
-
module BxBlockContactUs
-
class ContactFilter
-
DEFAULT_DATE_FORMAT = "%Y-%m-%d".freeze
-
-
attr_accessor :active_record, :query_params, :date_format
-
-
# Sample query_params:
-
# {
-
# "account_id": 1,
-
# "name"=> {"comparator": "equals", "value": "test"},
-
# "email"=>{"comparator": "contains", "value": "demo"},
-
# "phone_nubmer"=>{"comparator": "starts_with", "value": "+91"},
-
# "description"=>{"comparator": "ends_with", "value": "test"},
-
# "created_at"=>{"comparator": "between", "from": "2020-09-01",
-
# "to": "2020-09-30"},
-
# "updated_at"=>{"comparator": "between", "from": "2020-09-01",
-
# "to": "2020-09-30"},
-
# }
-
def initialize(active_record, query_params,
-
date_format: DEFAULT_DATE_FORMAT)
-
@active_record = active_record
-
@query_params = query_params.permit!.to_h if query_params.present?
-
@date_format = date_format
-
end
-
-
def call
-
query_params.present? ?
-
active_record.where(query_string) : active_record.all
-
end
-
-
private
-
-
def query_string
-
query_str = ""
-
query_params.each_with_index do |(key, value), index|
-
query_str += query_string_for(key, value)
-
query_str += " AND " if index < query_params.length - 1
-
end
-
-
query_str
-
end
-
-
def query_string_for(attr_name, value_or_hash)
-
return "#{attr_name} = #{value_or_hash}" if !value_or_hash.is_a?(Hash)
-
-
value = value_or_hash[:value].to_s.downcase
-
case value_or_hash[:comparator]
-
when "equals"
-
"LOWER(#{attr_name}) = '#{value}'"
-
when "contains"
-
"LOWER(#{attr_name}) LIKE '%#{value}%'"
-
when "starts_with"
-
"LOWER(#{attr_name}) LIKE '#{value}%'"
-
when "ends_with"
-
"LOWER(#{attr_name}) LIKE '%#{value}'"
-
when "between"
-
from = to_date(value_or_hash[:from])
-
to = to_date(value_or_hash[:to])
-
-
"DATE(#{attr_name}) >= '#{from}' AND DATE(#{attr_name}) <= '#{to}'"
-
else
-
""
-
end
-
end
-
-
def to_date(date_string)
-
Date.strptime(date_string, date_format)
-
end
-
end
-
end
-
module BxBlockContentManagement
-
class AudioPodcastService
-
class << self
-
-
def create_content(row, content_params, parent=nil)
-
content_exist = BxBlockContentManagement::Content.find_by(id: row[:id])
-
if content_exist
-
content_exist.update(audio_podcast_params(row, content_params))
-
return content_exist
-
else
-
content = BxBlockContentManagement::Content.new(audio_podcast_params(row, content_params))
-
content.save
-
-
if content.errors.present?
-
if parent.present?
-
parent.add_errors(content.errors.full_messages.to_sentence, row[:heading], row[:sn], 'content', 'heading')
-
else
-
return {errors: content.errors.full_messages.to_sentence}
-
end
-
end
-
return content
-
end
-
end
-
-
private
-
-
def audio_podcast_params(row, content_params)
-
content_params = content_params.merge(
-
publish_date: row[:publish_date],
-
feature_article: row[:feature_article],
-
feature_video: row[:feature_video],
-
contentable_attributes: {heading: row[:heading], description: row[:description]}
-
)
-
if row[:image_attributes].present? and row[:image_attributes][:image].present?
-
content_params[:contentable_attributes][:image_attributes] = row[:image_attributes]&.to_unsafe_hash
-
end
-
if row[:audio_attributes].present? and row[:audio_attributes][:audio].present?
-
content_params[:contentable_attributes][:audio_attributes] = row[:audio_attributes]&.to_unsafe_hash
-
end
-
content_params
-
end
-
-
end
-
end
-
end
-
module BxBlockContentManagement
-
class BaseError < StandardError; end
-
class InvalidSheetHeaders < BaseError; end
-
-
module Base
-
extend BxBlockContentManagement::Interface
-
-
need_to_implement :import_data, :get_headers
-
-
def call(xlsx, sheet_name, error_tracker)
-
return unless xlsx.sheets.include?(sheet_name)
-
sheet = xlsx.sheet(sheet_name)
-
@sheet_headers = sheet.first
-
@sheet_content = []
-
@sheet_name = sheet_name
-
@error_tracker = error_tracker
-
-
begin
-
validate_headers!
-
process_sheet_content(sheet)
-
import_data
-
rescue BaseError => e
-
add_errors_to_tracker(e.message)
-
end
-
end
-
-
def add_errors(msg, name, sn, object_name, identifier)
-
@error_tracker.add_errors(
-
"In #{@sheet_name}: Their was error occurred in saving #{object_name} with #{identifier} " \
-
"'#{name}' in row with sn: '#{sn}', errors: #{msg}"
-
)
-
end
-
-
def add_errors_to_tracker(msg)
-
@error_tracker.add_errors(msg)
-
end
-
-
def strip(str)
-
str.to_s.strip
-
end
-
-
def strip_downcase(str)
-
strip(str).downcase
-
end
-
-
def validate_headers!
-
unless verify_headers?
-
raise InvalidSheetHeaders.new(get_missing_header_message)
-
end
-
end
-
-
def process_sheet_content(sheet)
-
sheet.each(get_headers) do |row|
-
@sheet_content << row
-
end
-
@sheet_content.shift
-
end
-
-
def verify_headers?
-
missing_headers.blank?
-
end
-
-
def missing_headers
-
get_headers.values - @sheet_headers
-
end
-
-
def build_attributes(row, trnsf_keys = transform_keys)
-
attributes = {}
-
get_headers.each do |k,_|
-
value = row[k]
-
key = trnsf_keys[k] || k
-
if value.is_a?(String)
-
attributes[key] = strip(value)
-
else
-
attributes[key] = value
-
end
-
end
-
attributes
-
end
-
-
def transform_keys
-
{}
-
end
-
-
def get_missing_header_message
-
missing_sheet_headers = missing_headers.to_sentence
-
"Missing headers in sheet #{@sheet_name}: #{missing_sheet_headers}"
-
end
-
end
-
end
-
module BxBlockContentManagement
-
module BuildContentType
-
class << self
-
-
def call(content_types = content_types_array)
-
content_types.each do |content_type|
-
BxBlockContentManagement::ContentType.where('lower(name) = ?', content_type[:name].downcase)
-
.or(BxBlockContentManagement::ContentType.where(identifier: content_type[:identifier]))
-
.first_or_create(content_type)
-
end
-
end
-
-
private
-
-
def content_types_array
-
[
-
{name: "News Articles", type: "Text", identifier: "news_article"},
-
{name: "Blogs", type: "Text", identifier: "blog"},
-
{name: "Videos (short)", type: "Videos", identifier: "video_short"},
-
{name: "Videos (full length)", type: "Videos", identifier: "video_full"},
-
{name: "Live Streaming", type: "Live Stream", identifier: "live_streaming"},
-
{name: "Audio Podcast", type: "AudioPodcast", identifier: "audio_podcast"},
-
{name: "Quiz (No analytics)", type: "Test", identifier: "quiz"},
-
{name: "Assessment (with analytics)", type: "Test", identifier: "assessment"},
-
{name: "Study Materials (PDFs/ PPTs/ Word)", type: "Epub", identifier: "study_material"}
-
]
-
end
-
-
end
-
end
-
end
-
module BxBlockContentManagement
-
module BuildRole
-
class << self
-
end
-
end
-
end
-
module BxBlockContentManagement
-
class BulkDataImportService
-
def store_data(xlsx, current_user_id)
-
error_tracker = ErrorTracker.new
-
-
BxBlockContentManagement::CategoryImportService.call(xlsx, error_tracker)
-
BxBlockContentManagement::SubCategoryImportService.call(xlsx, error_tracker)
-
BxBlockContentManagement::ContentImportService.call(xlsx, error_tracker, current_user_id)
-
BxBlockContentManagement::PartnerImportService.call(xlsx, error_tracker)
-
-
if error_tracker.success?
-
return {success: true}
-
else
-
return {success: false, errors: error_tracker.get_errors}
-
end
-
end
-
end
-
end
-
require 'roo'
-
-
module BxBlockContentManagement
-
class BulkUploadService
-
class << self
-
-
def store_data(file_obj_path, current_user_id)
-
xlsx = Roo::Spreadsheet.open(file_obj_path)
-
sheets_name_arr = xlsx.sheets
-
ActiveRecord::Base.transaction do
-
@response = BxBlockContentManagement::BulkDataImportService.new.store_data(xlsx, current_user_id)
-
unless @response[:success]
-
@response
-
raise ActiveRecord::Rollback
-
end
-
end
-
return @response
-
end
-
end
-
end
-
end
-
# BxBlockContentManagement::CategoryImportService.call(xlsx, error_tracker)
-
-
module BxBlockContentManagement
-
class CategoryImportService
-
extend Base
-
-
class << self
-
-
def call(xlsx, error_tracker)
-
super(xlsx, 'category_sheet', error_tracker)
-
end
-
-
def import_data
-
@sheet_content.each do |sheet_content|
-
# Find or Create category
-
category = BxBlockCategories::Category.where("lower(name) = ? ", strip_downcase(sheet_content[:name])).first
-
if category.present?
-
category.rank = sheet_content[:rank]
-
else
-
category = BxBlockCategories::Category.new(category_params(sheet_content[:name], sheet_content[:rank]))
-
end
-
-
category.save
-
if category.errors.present?
-
add_errors(
-
category.errors.full_messages.to_sentence,
-
sheet_content[:name], sheet_content[:sn], 'category', 'name'
-
)
-
end
-
end
-
end
-
-
def get_headers
-
{
-
sn: 'sn',
-
name: 'name',
-
rank: 'rank'
-
}
-
end
-
-
private
-
-
def category_params(name, rank)
-
{
-
name: strip_downcase(name),
-
rank: rank
-
}
-
end
-
-
end
-
end
-
end
-
# BxBlockContentManagement::CategoryImportService.call(xlsx, error_tracker)
-
-
module BxBlockContentManagement
-
class ContentImportService
-
extend Base
-
-
class << self
-
-
def call(xlsx, error_tracker, current_user_id)
-
@current_user_id = current_user_id
-
super(xlsx, 'content_sheet', error_tracker)
-
end
-
-
def import_data
-
@sheet_content.each do |sheet_content|
-
build_value = build_attributes(sheet_content)
-
-
category = BxBlockCategories::Category.find_by('lower(name) = ?', strip_downcase(build_value[:category_name]))
-
unless category.present?
-
add_errors(
-
"can't find category with this name '#{build_value[:category_name]}'",
-
sheet_content[:heading], sheet_content[:sn], 'content', 'heading'
-
)
-
end
-
-
sub_category = BxBlockCategories::SubCategory.find_by(
-
'lower(name) = ?', strip_downcase(build_value[:sub_category_name])
-
)
-
unless sub_category.present?
-
add_errors(
-
"can't find sub category with this name '#{build_value[:sub_category_name]}'",
-
sheet_content[:heading], sheet_content[:sn], 'content', 'heading'
-
)
-
end
-
-
content_type = BxBlockContentManagement::ContentType.find_by(
-
'lower(name) = ?', strip_downcase(build_value[:content_type_name])
-
)
-
unless content_type.present?
-
add_errors(
-
"can't find content type with this name '#{build_value[:content_type]}'",
-
sheet_content[:heading], sheet_content[:sn], 'content', 'heading'
-
)
-
end
-
-
language = BxBlockLanguageOptions::Language.find_by(
-
'lower(name) = ?', strip_downcase(build_value[:language])
-
)
-
unless language.present?
-
add_errors(
-
"can't find language with this name '#{build_value[:category_name]}'",
-
sheet_content[:heading], sheet_content[:sn], 'content', 'heading'
-
)
-
end
-
-
tags = build_value[:tags]&.split(",")
-
-
if category.present? && sub_category.present? && content_type.present? && language.present?
-
BxBlockContentManagement::CreateContentService.create_content(
-
content_type, sheet_content, sub_category, language, category, tags, @current_user_id, self
-
)
-
end
-
end
-
end
-
-
def get_headers
-
{
-
sn: 'sn',
-
id: 'id',
-
category_name: 'category_name',
-
sub_category_name: 'sub_category_name',
-
tags: 'tags',
-
searchable_text: 'searchable_text',
-
publish_date: 'publish_date',
-
status: 'status',
-
language: 'language',
-
content_type_name: "content_type_name",
-
author_id: "author_id",
-
heading: "heading",
-
description: "description",
-
affiliation: "affiliation",
-
separate_section: "separate_section",
-
hyperlink: "hyperlink"
-
}
-
end
-
end
-
end
-
end
-
# BxBlockContentManagement::CategoryImportService.call(xlsx, error_tracker)
-
-
module BxBlockContentManagement
-
class CreateContentService
-
-
class << self
-
-
def create_content(content_type, sheet_content, sub_category, language, category, tags, parent_error_tracker=nil)
-
case content_type.type
-
when "Text"
-
BxBlockContentManagement::TextService.create_content(
-
sheet_content,
-
create_content_params(
-
sheet_content,
-
sub_category.id,
-
language.id,
-
category.id,
-
content_type.id,
-
tags
-
),
-
content_type.identifier,
-
parent_error_tracker
-
)
-
when "Videos"
-
BxBlockContentManagement::VideoService.create_content(
-
sheet_content,
-
create_content_params(
-
sheet_content,
-
sub_category.id,
-
language.id,
-
category.id,
-
content_type.id,
-
tags
-
),
-
parent_error_tracker)
-
when "Live Stream"
-
BxBlockContentManagement::LiveStreamService.create_content(
-
sheet_content,
-
create_content_params(
-
sheet_content,
-
sub_category.id,
-
language.id,
-
category.id,
-
content_type.id,
-
tags
-
),
-
parent_error_tracker
-
)
-
when "AudioPodcast"
-
BxBlockContentManagement::AudioPodcastService.create_content(
-
sheet_content,
-
create_content_params(
-
sheet_content,
-
sub_category.id,
-
language.id,
-
category.id,
-
content_type.id,
-
tags
-
),
-
parent_error_tracker
-
)
-
when "Test"
-
BxBlockContentManagement::TestService.create_content(
-
sheet_content,
-
create_content_params(
-
sheet_content,
-
sub_category.id,
-
language.id,
-
category.id,
-
content_type.id,
-
tags
-
),
-
parent_error_tracker
-
)
-
when "Epub"
-
BxBlockContentManagement::EpubService.create_content(
-
sheet_content,
-
create_content_params(
-
sheet_content,
-
sub_category.id,
-
language.id,
-
category.id,
-
content_type.id,
-
tags
-
),
-
parent_error_tracker
-
)
-
end
-
end
-
-
private
-
-
def create_content_params(content, sub_category_id, language_id, category_id, content_type_id, tags)
-
{
-
category_id: category_id,
-
sub_category_id: sub_category_id,
-
language_id: language_id,
-
searchable_text: content[:searchable_text],
-
content_type_id: content_type_id,
-
status: content[:status],
-
tag_list: tags
-
}
-
end
-
end
-
end
-
end
-
module BxBlockContentManagement
-
class EpubService
-
class << self
-
-
def create_content(row, content_params, parent_error_tracker=nil)
-
content_exist = BxBlockContentManagement::Content.find_by(id: row[:id])
-
if content_exist
-
content_exist.update(epub_params(row, content_params))
-
return content_exist
-
else
-
content = BxBlockContentManagement::Content.new(epub_params(row, content_params))
-
content.save
-
if content.errors.present?
-
if parent_error_tracker.present?
-
parent_error_tracker.add_errors(
-
content.errors.full_messages.to_sentence, row[:heading], row[:sn], 'content', 'heading'
-
)
-
else
-
return {errors: content.errors.full_messages.to_sentence}
-
end
-
end
-
return content
-
end
-
end
-
-
private
-
-
def epub_params(row, content_params)
-
content_params = content_params.merge(
-
publish_date: row[:publish_date],
-
feature_article: row[:feature_article],
-
feature_video: row[:feature_video],
-
contentable_attributes: { heading: row[:heading], description: row[:description] }
-
)
-
if row[:pdfs_attributes].present?
-
content_params[:contentable_attributes][:pdfs_attributes] = row[:pdfs_attributes]&.to_unsafe_hash
-
end
-
content_params
-
end
-
-
end
-
end
-
end
-
module BxBlockContentManagement
-
class ErrorTracker
-
def initialize
-
@errors = []
-
end
-
-
def add_errors(errors)
-
@errors.push(*errors)
-
end
-
-
def error?
-
@errors.any?
-
end
-
-
def success?
-
!error?
-
end
-
-
def get_errors
-
@errors
-
end
-
end
-
end
-
module BxBlockContentManagement
-
module Interface
-
def need_to_implement(*method_names)
-
method_names.each do |method_name|
-
define_method(method_name) { |*args|
-
raise "Not implemented #{method_name}, please add method to your module."
-
}
-
end
-
end
-
end
-
end
-
module BxBlockContentManagement
-
class LiveStreamService
-
class << self
-
-
def create_content(row, content_params, parent_error_tracker=nil)
-
content_exist = BxBlockContentManagement::Content.find_by(id: row[:id])
-
-
if content_exist
-
content_exist.update(live_stream_params(row, content_params))
-
return content_exist
-
else
-
content = BxBlockContentManagement::Content.new(live_stream_params(row, content_params))
-
content.save
-
if content.errors.present?
-
if parent_error_tracker.present?
-
error_tracker.add_errors(
-
content.errors.full_messages.to_sentence, row[:heading], row[:sn], 'content', 'heading'
-
)
-
else
-
return {errors: content.errors.full_messages.to_sentence}
-
end
-
end
-
return content
-
end
-
end
-
-
private
-
-
def live_stream_params(row, content_params)
-
content_params.merge(
-
publish_date: row[:publish_date],
-
feature_article: row[:feature_article],
-
feature_video: row[:feature_video],
-
contentable_attributes: {
-
headline: row[:heading] || row[:headline],
-
description: row[:description],
-
comment_section: row[:separate_section] || row[:comment_section]
-
}
-
)
-
end
-
-
end
-
end
-
end
-
# BxBlockContentManagement::CategoryImportService.call(xlsx, error_tracker)
-
-
module BxBlockContentManagement
-
class PartnerImportService
-
extend Base
-
-
class << self
-
-
def call(xlsx, error_tracker)
-
super(xlsx, 'partner_sheet', error_tracker)
-
end
-
-
def import_data
-
-
@sheet_content.each do |sheet_content|
-
-
build_value = build_attributes(sheet_content)
-
category_arr = []
-
build_value[:categories_name].split(", ").each do |category_name|
-
category = BxBlockCategories::Category.find_by('lower(name) = ?', strip_downcase(category_name))
-
unless category.present?
-
add_errors(
-
"can't find category with this name",
-
sheet_content[:name], sheet_content[:sn], 'partner', 'name'
-
)
-
else
-
category_arr << category.id
-
end
-
end
-
-
sub_category_arr = []
-
-
build_value[:sub_categories_name].split(", ").each do |sub_category_name|
-
sub_category = BxBlockCategories::SubCategory.find_by(
-
'lower(name) = ?', strip_downcase(sub_category_name)
-
)
-
unless sub_category.present?
-
add_errors(
-
"can't find sub category with this name",
-
sheet_content[:name], sheet_content[:sn], 'partner', 'name'
-
)
-
else
-
sub_category_arr << sub_category.id
-
end
-
end
-
-
content_type_arr = []
-
-
build_value[:content_types_name].split(", ").each do |content_type_name|
-
content_type = BxBlockContentManagement::ContentType.find_by(
-
'lower(name) = ?', strip_downcase(content_type_name)
-
)
-
unless content_type.present?
-
add_errors(
-
"can't find content type with this name",
-
sheet_content[:name], sheet_content[:sn], 'partner', 'name'
-
)
-
else
-
content_type_arr << content_type.id
-
end
-
end
-
end
-
end
-
-
def get_headers
-
{
-
sn: 'sn',
-
email: 'email',
-
name: 'name',
-
spoc_name: 'spoc_name',
-
address: 'address',
-
categories_name: 'categories_name',
-
sub_categories_name: 'sub_categories_name',
-
content_types_name: 'content_types_name',
-
spoc_contact: 'spoc_contact',
-
status: 'status',
-
partner_type: 'partner_type',
-
partnership_type: 'partnership_type',
-
partner_margins_per: 'partner_margins_per',
-
tax_margins: 'tax_margins',
-
bank_ifsc: 'bank_ifsc',
-
account_number: 'account_number',
-
account_name: 'account_name',
-
bank_name: 'bank_name'
-
}
-
end
-
-
private
-
-
def create_admin_attributes(name, email, spoc_name, role, address, spoc_contact, status,
-
partner_type, partnership_type, partner_margins_per, tax_margins,
-
bank_ifsc, account_number, account_name, bank_name, category_ids,
-
sub_category_ids, content_type_ids)
-
{
-
email: email,
-
role: role,
-
partner_attributes:{
-
name: name,
-
address: address,
-
spoc_name: spoc_name,
-
spoc_contact: spoc_contact,
-
category_ids: category_ids,
-
sub_category_ids: sub_category_ids,
-
content_type_ids: content_type_ids,
-
status: status,
-
partner_type: partner_type,
-
partnership_type: partnership_type,
-
partner_margins_per: partner_margins_per,
-
tax_margins: tax_margins,
-
bank_ifsc: bank_ifsc,
-
account_number: account_number,
-
account_name: account_name,
-
bank_name: bank_name
-
}
-
}
-
end
-
-
end
-
end
-
end
-
# BxBlockContentManagement::CategoryImportService.call(xlsx, error_tracker)
-
-
module BxBlockContentManagement
-
class SubCategoryImportService
-
extend Base
-
-
class << self
-
-
def call(xlsx, error_tracker)
-
super(xlsx, 'sub_category_sheet', error_tracker)
-
end
-
-
def import_data
-
-
@sheet_content.each do |sheet_content|
-
category_new = nil
-
parent = nil
-
# Find or Create category
-
if sheet_content[:parent_name].present?
-
parent = BxBlockCategories::SubCategory.find_by(
-
'lower(name) = ?', strip_downcase(sheet_content[:parent_name])
-
)
-
add_errors(
-
"can't find parent with name '#{sheet_content[:parent_name]}'",
-
sheet_content[:name], sheet_content[:sn], 'sub category', 'name'
-
) unless parent.present?
-
end
-
if sheet_content[:category_name].present?
-
category_new = find_category(sheet_content[:category_name])
-
unless category_new.present?
-
add_errors(
-
"can't find category with name '#{sheet_content[:parent_name]}'",
-
sheet_content[:name], sheet_content[:sn], 'sub category', 'name'
-
)
-
else
-
sub_category = create_sub_category(sheet_content[:name], category_new, parent)
-
if sub_category.errors.present?
-
add_errors(
-
sub_category.errors.full_messages.to_sentence,
-
sheet_content[:name], sheet_content[:sn], 'sub category', 'name'
-
)
-
end
-
end
-
else
-
sub_category = create_sub_category(sheet_content[:name], category_new, parent)
-
if sub_category.errors.present?
-
add_errors(
-
sub_category.errors.full_messages.to_sentence,
-
sheet_content[:name], sheet_content[:sn], 'sub category', 'name'
-
)
-
end
-
end
-
end
-
end
-
-
def get_headers
-
{
-
sn: 'sn',
-
name: 'name',
-
category_name: 'category_name',
-
parent_name: 'parent_name',
-
rank: 'rank'
-
}
-
end
-
-
private
-
-
def find_category(c_name)
-
BxBlockCategories::Category.find_by('lower(name) = ?', strip_downcase(c_name))
-
end
-
-
def create_sub_category(sc_name, category=nil, parent=nil)
-
sub_category_exist = BxBlockCategories::SubCategory.find_by('lower(name) = ?', strip_downcase(sc_name))
-
if sub_category_exist.blank?
-
sub_category_exist = BxBlockCategories::SubCategory.new()
-
end
-
sub_category_exist.update(sub_category_params(sc_name, parent, category))
-
sub_category_exist
-
end
-
-
def sub_category_params(sc_name, parent, category=nil)
-
-
params = {
-
name: sc_name,
-
parent_id: parent&.id
-
}
-
params.merge!(categories: [category]) if category.present?
-
params
-
end
-
-
end
-
end
-
end
-
module BxBlockContentManagement
-
class TestService
-
class << self
-
-
def create_content(row, content_params, parent_error_tracker=nil)
-
content_exist = BxBlockContentManagement::Content.find_by(id: row[:id])
-
if content_exist
-
content_exist.update(test_params(row, content_params))
-
return content_exist
-
else
-
content = BxBlockContentManagement::Content.new(test_params(row, content_params))
-
content.save
-
if content.errors.present?
-
if parent_error_tracker.present?
-
parent_error_tracker.add_errors(
-
content.errors.full_messages.to_sentence, row[:heading], row[:sn], 'content', 'heading'
-
)
-
else
-
return {errors: content.errors.full_messages.to_sentence}
-
end
-
end
-
return content
-
end
-
end
-
-
private
-
-
def test_params(row, content_params)
-
content_params.merge(
-
publish_date: row[:publish_date],
-
feature_article: row[:feature_article],
-
feature_video: row[:feature_video],
-
contentable_attributes: { headline: row[:heading] || row[:headline], description: row[:description] }
-
)
-
end
-
-
end
-
end
-
end
-
module BxBlockContentManagement
-
class TextService
-
class << self
-
def create_content(row, content_params, identifier, parent_error_tracker=nil)
-
content_exist = BxBlockContentManagement::Content.find_by(id: row[:id])
-
if content_exist
-
if content_exist.content_type.identifier == 'blog'
-
parent_error_tracker.present? ? save_with_author(row, parent_error_tracker) : save_with_author(row)
-
content_exist.update(text_content_params(row, content_params).merge(author_id: row[:author_id]))
-
else
-
content_exist.update(text_content_params(row, content_params))
-
end
-
return content_exist
-
else
-
if identifier == 'blog'
-
save_with_author(row, parent_error_tracker)
-
content = BxBlockContentManagement::Content.new(
-
text_content_params(row, content_params
-
).merge(author_id: row[:author_id]))
-
content.save
-
else
-
content = BxBlockContentManagement::Content.new(text_content_params(row, content_params))
-
content.save
-
end
-
-
if content.errors.present?
-
if parent_error_tracker.present?
-
parent_error_tracker.add_errors(
-
content.errors.full_messages.to_sentence, row[:heading], row[:sn], 'content', 'heading'
-
)
-
else
-
return {errors: content.errors.full_messages.to_sentence}
-
end
-
end
-
return content
-
end
-
end
-
-
private
-
-
def text_content_params(row, content_params)
-
content_params = content_params.merge(
-
publish_date: row[:publish_date],
-
feature_article: row[:feature_article],
-
feature_video: row[:feature_video],
-
contentable_attributes: {
-
headline: row[:heading] || row[:headline],
-
content: row[:description] || row[:content],
-
hyperlink: row[:hyperlink],
-
affiliation: row[:affiliation]
-
}
-
)
-
if row[:images_attributes].present?
-
content_params[:contentable_attributes][:images_attributes] = row[:images_attributes]&.to_unsafe_hash
-
end
-
if row[:videos_attributes].present?
-
content_params[:contentable_attributes][:videos_attributes] = row[:videos_attributes]&.to_unsafe_hash
-
end
-
content_params
-
end
-
-
def save_with_author(row, parent_error_tracker=nil)
-
@author = BxBlockContentManagement::Author.find_by(id: row[:author_id])
-
(parent_error_tracker ? parent_error_tracker.add_errors(
-
"author not find with id '#{row[:author_id]}'",
-
row[:heading],
-
row[:sn],
-
'content',
-
'heading'
-
) : (return {errors: "author not find"})
-
) unless @author.present?
-
end
-
-
end
-
end
-
end
-
module BxBlockContentManagement
-
class VideoService
-
class << self
-
-
def create_content(row, content_params, parent_error_tracker=nil)
-
content_exist = BxBlockContentManagement::Content.find_by(id: row[:id])
-
if content_exist
-
content_exist.update(video_content_params(row, content_params))
-
return content_exist
-
else
-
content = BxBlockContentManagement::Content.new(video_content_params(row, content_params))
-
content.save
-
if content.errors.present?
-
if parent_error_tracker
-
parent_error_tracker.add_errors(
-
content.errors.full_messages.to_sentence, row[:heading], row[:sn], 'content', 'heading'
-
)
-
else
-
return {errors: content.errors.full_messages.to_sentence}
-
end
-
end
-
return content
-
end
-
end
-
-
private
-
-
def video_content_params(row, content_params)
-
content_params = content_params.merge(
-
publish_date: row[:publish_date],
-
feature_article: row[:feature_article],
-
feature_video: row[:feature_video],
-
contentable_attributes: {
-
headline: row[:heading] || row[:headline],
-
description: row[:description],
-
separate_section: row[:separate_section]
-
}
-
)
-
if row[:image_attributes].present?
-
content_params[:contentable_attributes][:image_attributes] = row[:image_attributes]&.to_unsafe_hash
-
end
-
if row[:video_attributes].present?
-
content_params[:contentable_attributes][:video_attributes] = row[:video_attributes]&.to_unsafe_hash
-
end
-
content_params
-
end
-
end
-
end
-
end
-
module BxBlockFedexIntegration
-
class ShipmentAttributesCreation
-
-
attr_accessor :order, :user, :hyperpay, :shipping_address
-
-
def initialize order, hyperpay
-
@order = order
-
@user = order.account
-
@hyperpay = hyperpay
-
@shipping_address = order.delivery_addresses.delivery_add.first
-
end
-
-
def call
-
{
-
"shipments_attributes": [{
-
"full_truck": false,
-
"load_description": "Dummy load description",
-
"cod_value_attributes": {
-
"amount": order.source == 'cod' ? order.total : nil,
-
"currency": hyperpay.present? ? hyperpay['data']['currency'] : nil
-
},
-
"shipment_value_attributes": {
-
"amount": order.source == 'online' ? order.total : nil,
-
"currency": hyperpay.present? ? hyperpay['data']['currency'] : nil
-
},
-
"delivery_attributes": {
-
"address": shipping_address.address,
-
"city": shipping_address.city,
-
"country": shipping_address.country,
-
"email": user.email,
-
"name": "#{user.first_name} #{user.last_name}",
-
"phone": user.phone_number,
-
"instructions": "delivery instructions",
-
"arrival_window_attributes": {
-
"begin_at": Time.current,
-
"end_at": Time.current + 7.days
-
},
-
"coordinate_attributes": {
-
"latitude": shipping_address.latitude,
-
"longitude": shipping_address.longitude
-
}
-
},
-
"pickup_attributes": {
-
"address": "18, Vijay Nagar, Indore",
-
"city": "Indore",
-
"country": "India",
-
"email": "pickup.demo@mailinator.com",
-
"name": "Pickup user",
-
"phone": "1234567891",
-
"instructions": "pickup instructions",
-
"arrival_window_attributes": {
-
"begin_at": "2020-10-09 07:13:07 UTC",
-
"end_at": "2020-10-15 07:13:07 UTC"
-
},
-
"coordinate_attributes": {
-
"latitude": "22.759146",
-
"longitude": "75.891044"
-
}
-
},
-
"items_attributes": [
-
{
-
"weight": total_weight,
-
"quantity": order_quantity,
-
"stackable": true,
-
"item_type": "PALLET",
-
"dimension_attributes": {
-
"height": 1,
-
"length": 10,
-
"width": 10
-
}
-
}
-
]
-
}]
-
}
-
end
-
-
def total_weight
-
BxBlockCatalogue::Catalogue.joins(
-
"LEFT JOIN order_items ON order_items.catalogue_id = catalogues.id"
-
).where(
-
id: order.order_items.pluck(:catalogue_id)
-
).group("catalogues.id").sum(&:weight).to_f
-
end
-
-
def order_quantity
-
order.order_items.group('order_items.id').sum(&:quantity).to_i
-
end
-
-
end
-
end
-
module BxBlockLanguageOptions
-
class BuildLanguages
-
class << self
-
-
def call(languages = languages_array)
-
languages.each do |language|
-
BxBlockLanguageOptions::Language.where(
-
'lower(name) = ?', language[:name].downcase
-
).first_or_create(name: language[:name], language_code: language[:language_code])
-
end
-
end
-
-
private
-
-
def languages_array
-
[
-
{name: "Hindi", language_code: "hi"},
-
{name: "English", language_code: "en"},
-
{name: "Telugu", language_code: "te"},
-
{name: "Tamil", language_code: "ta"},
-
{name: "Marathi", language_code: "mr"},
-
{name: "Bangla", language_code: "bn"},
-
{name: "Gujarati", language_code: "gu"},
-
{name: "Oriya", language_code: "or"}
-
]
-
end
-
-
end
-
end
-
end
-
module BxBlockLanguageOptions
-
class CreateAndUpdateTranslations
-
class << self
-
-
def call
-
translations = YAML.load_file(Rails.root.join("config", "locales/en.yml"))
-
en_translations = flatten_hash(translations["en"])
-
en_translations.each do |key, value|
-
application_message = BxBlockLanguageOptions::ApplicationMessage.find_by(name: key)
-
unless application_message.present?
-
BxBlockLanguageOptions::ApplicationMessage.create(
-
name: key, translations_attributes: [ {message: value, locale: "en"} ]
-
)
-
end
-
end
-
end
-
-
private
-
def flatten_hash(param, prefix=nil)
-
param.each_pair.reduce({}) do |a, (k, v)|
-
v.is_a?(Hash) ? a.merge(flatten_hash(v, "#{prefix}#{k}.")) : a.merge("#{prefix}#{k}" => v)
-
end
-
end
-
end
-
end
-
end
-
require 'roo'
-
-
module BxBlockLanguageOptions
-
class ImportDataService
-
class << self
-
-
def store_data(file_obj_path)
-
xlsx = Roo::Spreadsheet.open(file_obj_path)
-
sheets_name_arr = xlsx.sheets
-
unless sheets_name_arr.include?("translations_sheet")
-
return {success: false, error: "Please add translations sheet"}
-
end
-
ActiveRecord::Base.transaction do
-
@response = BxBlockLanguageOptions::TranslationDataImportService.new.store_data(xlsx)
-
unless @response[:success]
-
raise ActiveRecord::Rollback
-
end
-
end
-
return @response
-
end
-
-
end
-
end
-
end
-
module BxBlockLanguageOptions
-
class SerializeTranslations
-
class << self
-
-
def call(application_messages)
-
serialized_hash = {}
-
application_messages.find_each do |application_message|
-
serialized_hash[application_message.name] = application_message.message
-
end
-
serialized_hash
-
end
-
end
-
end
-
end
-
# BxBlockLanguageOptions::SetAvailableLocales.call
-
module BxBlockLanguageOptions
-
class SetAvailableLocales
-
class << self
-
def call
-
language_codes = [I18n.default_locale.to_s]
-
language_codes.push(
-
*BxBlockLanguageOptions::Language.pluck(:language_code).compact
-
) if BxBlockLanguageOptions::Language.table_exists? rescue false
-
I18n.available_locales = language_codes.uniq
-
end
-
end
-
end
-
end
-
module BxBlockLanguageOptions
-
class TranslationDataImportService
-
def store_data(xlsx)
-
arr = []
-
translations_data = xlsx.sheet("translations_sheet")
-
unless translations_data.count > 1
-
return {success: false, error: "No data present in translations sheet"}
-
end
-
-
success, missing_headers = validate_headers(translations_data.first)
-
unless success
-
return {success: false, error: "missing headers: #{missing_headers} in translations sheet"}
-
end
-
-
translations_data.each(headers) do |row|
-
arr << row
-
end
-
-
arr[1..].each do |arr2|
-
key_error(arr2)
-
serial_number_error(sn)
-
-
application_message = BxBlockLanguageOptions::ApplicationMessage.find_or_initialize_by(name: arr2[:key])
-
I18n.available_locales.each do |locale|
-
if application_message.id.present?
-
translation = application_message.translations.find_or_initialize_by(locale: locale.to_s)
-
translation.message = arr2[locale].to_s
-
unless translation.save
-
return {
-
success: false,
-
error: "Some error occured in Application Message data in row- #{arr2[:sn]} ->" \
-
" #{translation.errors.full_messages} "
-
}
-
end
-
else
-
application_message.translations_attributes= [{message: arr2[locale], locale: locale.to_s}]
-
end
-
unless application_message.save
-
return {
-
success: false,
-
error: "Some error occured in Application Message data in row- #{arr2[:sn]} ->" \
-
" #{application_message.errors.full_messages} "
-
}
-
end
-
end
-
end
-
return {success: true}
-
end
-
-
private
-
-
def key_error(arr2)
-
return {
-
success: false,
-
error: "key not present in translations sheet"
-
} unless arr2[:key].present?
-
end
-
-
def serial_number_error(sn)
-
return {
-
success: false,
-
error: "key -#{ arr2[:key] } serial number not present in translations sheet"
-
} unless arr2[:sn].present?
-
end
-
-
def validate_headers(sheet_headers)
-
missing_headers = headers.values - sheet_headers
-
[missing_headers.blank?, missing_headers.join(', ')]
-
end
-
-
def headers
-
available_headers = {sn: 'sn', key: 'key'}
-
BxBlockLanguageOptions::Language.pluck(:language_code).each do |language_code|
-
available_headers.merge!("#{language_code}": language_code.to_s)
-
end
-
available_headers
-
end
-
end
-
end
-
module BxBlockNavmenu
-
class Create
-
def initialize(attributes)
-
@attributes = attributes
-
end
-
-
def execute
-
ActiveRecord::Base.transaction do
-
@attributes.each do |position, items|
-
navigation_menu =
-
NavigationMenu.find_or_initialize_by(position: position)
-
navigation_menu.items = items
-
navigation_menu.save!
-
end
-
end
-
NavigationMenu.all
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
module BxBlockOrderManagement
-
class AddAddressToOrder
-
attr_accessor :params, :user, :order, :delivery_address, :billing_address
-
-
def initialize(params, user)
-
@params = params
-
@user = user
-
@order = Order.find_by(account_id: @user.id, id: params[:order_id])
-
end
-
-
def call
-
if params.present?
-
set_delivery_address
-
if is_address_correct? && delivery_address.save
-
if delivery_address.is_default
-
DeliveryAddress.rest_addresses(delivery_address.id).where(
-
account_id: user.id
-
).update_all(is_default: false)
-
end
-
-
delivery_address_ids = order.delivery_addresses.where(
-
address_for: delivery_address.address_for
-
).pluck(:id)
-
-
order.delivery_address_orders.address_ids(delivery_address_ids).destroy_all if delivery_address_ids.present?
-
-
order.delivery_addresses << delivery_address if order.delivery_addresses.where(id: delivery_address.id).blank?
-
if billing_address.present? && billing_address.save
-
-
if billing_address.is_default
-
DeliveryAddress.rest_addresses(billing_address.id).where(
-
account_id: user.id
-
).update_all(is_default: false)
-
end
-
-
billing_address_ids = order.delivery_addresses.where(
-
address_for: billing_address.address_for
-
).pluck(:id)
-
-
if delivery_address_ids.present?
-
order.delivery_address_orders.address_ids(
-
billing_address_ids
-
).destroy_all
-
end
-
-
order.delivery_addresses << billing_address
-
end
-
-
OpenStruct.new(
-
success?: true,
-
data: {},
-
msg: "Address added successfully",
-
code: 200
-
)
-
else
-
OpenStruct.new(
-
success?: false,
-
data: nil,
-
msg: "Ooops, Sorry it seems like your address doesn't cover store's delivery area. " \
-
"Try again with valid address",
-
code: 404
-
)
-
end
-
else
-
OpenStruct.new(
-
success?: false,
-
data: nil,
-
msg: "Ooops, Sorry it seems like you didn't provide the delivery address.",
-
code: 404
-
)
-
end
-
end
-
-
private
-
-
def is_address_correct?
-
delivery_address.present?
-
end
-
-
def address_params
-
params.permit(
-
:name, :flat_no, :address, :address_line_2, :zip_code, :phone_number, :is_default,
-
:state, :country, :city, :landmark
-
)
-
end
-
-
def billing_params
-
params.require(:address).require(:billing_address).permit(
-
:name, :flat_no, :address, :address_line_2, :zip_code, :phone_number, :is_default,
-
:state, :country, :city, :landmark
-
)
-
end
-
-
def set_delivery_address
-
@del_address = DeliveryAddress.find_by(account_id: user.id, id: params[:address_id])
-
if @del_address.nil?
-
return OpenStruct.new(
-
success?: false,
-
data: nil,
-
msg: "Ooops, Sorry it seems like delivery address Id id not present.",
-
code: 404
-
)
-
end
-
-
@delivery_address = if params[:address_id]
-
DeliveryAddress.find_by(account_id: user.id, id: params[:address_id])
-
else
-
DeliveryAddress.new(address_params.merge({account_id: user.id}))
-
end
-
@delivery_address.is_default = true if DeliveryAddress.find_by(account_id: user.id).blank?
-
if params[:billing_same_as_shipping]
-
order.delivery_address_orders.destroy_all
-
@delivery_address.address_for = "billing and shipping"
-
elsif params[:address][:billing_address].present?
-
shipping_and_billing_ids = order.delivery_addresses.billing_and_shipping.pluck(:id)
-
order.delivery_address_orders.address_ids(shipping_and_billing_ids).destroy_all
-
@delivery_address.address_for = "shipping"
-
@billing_address = DeliveryAddress.new(billing_params.merge({account_id: user.id}))
-
@billing_address.is_default = true if DeliveryAddress.find_by(account_id: user.id).blank?
-
@billing_address.address_for = "billing"
-
end
-
end
-
end
-
end
-
# rubocop:enable Metrics/MethodLength, Metrics/AbcSize, Metrics/PerceivedComplexity, Naming/VariableNumber, Naming/PredicateName, Metrics/BlockNesting, Metrics/CyclomaticComplexity, Metrics/ClassLength
-
# frozen_string_literal: true
-
-
1
module BxBlockOrderManagement
-
1
class AddProduct
-
1
attr_accessor :params, :quantity, :catalogue, :order, :user, :catalogue_variant, :ebook_id, :bundle_management_id
-
-
1
def initialize(params, user)
-
3
@params = params
-
3
@quantity = params[:quantity]
-
# @catalogue_id = params[:catalogue_id]
-
# @catalogue = BxBlockCatalogue::Catalogue.find(@catalogue_id)
-
3
@ebook_id = params[:ebook_id]
-
3
@ebook = BxBlockBulkUploading::Ebook.find_by(id: @ebook_id)
-
# @catalogue_variant = @catalogue.catalogue_variants.find_by(id: params[:catalogue_variant_id])
-
3
@bundle_management_id = params[:bundle_management_id]
-
3
@bundle_management = BxBlockBulkUploading::BundleManagement.find_by(id: @bundle_management_id)
-
3
@user = user
-
end
-
-
1
def call
-
3
if params[:ebook_id].blank? && params[:bundle_management_id].blank?
-
OpenStruct.new(
-
success?: false,
-
data: nil,
-
msg: "Sorry, Item is not found for this product",
-
code: 404
-
)
-
3
elsif params[:bundle_management_id].blank? && params[:ebook_id].present?
-
2
create_order_item
-
1
elsif params[:ebook_id].blank? && params[:bundle_management_id].present?
-
1
create_order_item
-
end
-
end
-
-
1
private
-
-
# def product_not_available?
-
# check_order_qty = Order.includes(:order_items).where(order_items: {ebook_id: @ebook.id}).sum(:quantity)
-
-
# quantity.to_i > if @ebook.present?
-
# (@ebook.stock_qty.to_i - @ebook.block_qty.to_i - check_order_qty || 0)
-
# else
-
# (@ebook.stock_qty.to_i - @ebook.block_qty.to_i - check_order_qty || 0)
-
# end
-
# end
-
-
1
def order_item_params
-
3
params.permit(:ebook_id, :bundle_management_id, :order_id)
-
end
-
-
1
def card_params
-
{
-
number: params[:number],
-
exp_month: params[:exp_month],
-
exp_year: params[:exp_year],
-
cvc: params[:cvc]
-
}
-
end
-
-
1
def create_order_item
-
3
@order = if params[:cart_id].present?
-
1
Order.find_by_id(params[:cart_id])
-
else
-
2
Order.create!(
-
account_id: user.id,
-
status: "created",
-
# coupon_code_id: params[:coupon_code_id],
-
amount: params[:amount]
-
)
-
end
-
-
3
if order.blank?
-
OpenStruct.new(
-
success?: false,
-
data: nil,
-
msg: "Sorry, cart is not found",
-
code: 404
-
)
-
else
-
3
order.order_items.create!(order_item_params)
-
3
msg = "Item added in cart successfully" if params[:cart_id].present?
-
3
msg = "Order created successfully" unless params[:cart_id].present?
-
3
OpenStruct.new(success?: true, data: order, msg: msg, code: 200)
-
end
-
end
-
end
-
end
-
# rubocop:enable Metrics/MethodLength, Metrics/AbcSize
-
# frozen_string_literal: true
-
-
module BxBlockOrderManagement
-
class ApplyCoupon
-
attr_accessor :coupon_code, :cart_value, :order
-
-
def initialize(order, coupon, params)
-
@coupon_code = coupon
-
@order = order
-
@cart_value = params[:cart_value].to_f
-
end
-
-
def call
-
discount = if coupon_code.discount_type == "percentage"
-
((cart_value * coupon_code.discount) / 100)
-
else
-
coupon_code.discount
-
end
-
if discount < cart_value
-
discount_price = (cart_value - discount)&.round(2)
-
order.update(coupon_code_id: coupon_code.id, total: discount_price, applied_discount: discount)
-
OpenStruct.new(
-
success?: false,
-
msg: "Coupon applied to all items in the order with status in cart",
-
code: 200
-
)
-
else
-
discount_price = (discount - cart_value)&.round(2)
-
order.update(coupon_code_id: coupon_code.id, total: 0, applied_discount: discount)
-
coupon_code.update(discount:discount_price)
-
OpenStruct.new(
-
success?: false,
-
msg: "Coupon has still left discount of #{discount_price}",
-
code: 200
-
)
-
end
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
module BxBlockOrderManagement
-
class StateProcess
-
# optional args parameter can be omitted, but if you define initialize
-
# you must accept the model instance as the first parameter to it.
-
attr_accessor :order, :aasm, :user
-
-
def initialize(order, aasm)
-
@order = order
-
@aasm = aasm
-
@user = order.order.account if order.instance_of?(OrderItem)
-
@user = order.account if order.instance_of?(Order)
-
end
-
-
def call
-
event_name = aasm.current_event.to_s
-
if (Order::EVENTS.include? event_name) && order.instance_of?(Order)
-
a = "#{aasm.to_state}_at"
-
order.update(a => Time.current)
-
end
-
create_trackings if order.instance_of?(OrderItem)
-
if OrderStatus.new_statuses.pluck(:status).include? event_name.delete("!")
-
status_id = OrderStatus.find_or_create_by(status: event_name.delete("!")).id
-
order.update(order_status_id: status_id) unless order.order_status_id == status_id
-
end
-
end
-
-
private
-
-
def create_trackings
-
tracking = Tracking.find_or_create_by(date: DateTime.current, status: aasm.to_state.to_s)
-
order.order_trackings.create(tracking_id: tracking.id)
-
end
-
end
-
end
-
# rubocop:enable Metrics/AbcSize
-
# frozen_string_literal: true
-
-
1
module BxBlockOrderManagement
-
1
class UpdateCartValue
-
1
attr_accessor :order
-
-
1
def initialize(order, user)
-
3
@order = order
-
3
@user = user
-
end
-
-
1
def call
-
3
save_order
-
3
BxBlockOrderManagement::Validity.new(order_attributes, @user).check_cart_total if order.coupon_code.present?
-
end
-
-
1
def save_order
-
3
update_order_total
-
3
update_order_sub_total
-
3
order.save
-
end
-
-
1
private
-
-
1
def order_attributes
-
{
-
code: order.coupon_code.code,
-
cart_id: order.id,
-
cart_value: order.sub_total,
-
existing_cart: true
-
}
-
end
-
-
1
def update_order_total
-
3
order.total = order.total_price
-
3
order.total_after_shipping_charge
-
3
order.total_after_tax_charge
-
end
-
-
1
def update_order_sub_total
-
3
order.sub_total = order.sub_total_price
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
module BxBlockOrderManagement
-
class Validity
-
attr_accessor :params, :coupon_code, :cart_value, :order, :user
-
-
def initialize(params, user)
-
@params = params
-
@coupon_code = BxBlockCouponCg::CouponCode.find_by_code(params[:code])
-
@order = BxBlockOrderManagement::Order.find(params[:cart_id])
-
@cart_value = params[:cart_value].to_f
-
@user = user
-
end
-
-
def check_cart_total
-
if coupon_code.min_cart_value && cart_value < coupon_code.min_cart_value
-
respond_error("min")
-
elsif coupon_code.max_cart_value && cart_value > coupon_code.max_cart_value
-
respond_error("max")
-
else
-
calculate_discount
-
end
-
end
-
-
def calculate_discount
-
discount = if coupon_code.discount_type == "percentage"
-
((cart_value * coupon_code.discount) / 100)
-
else
-
coupon_code.discount
-
end
-
discount_price = (cart_value - discount)&.round(2)
-
if discount < cart_value
-
order.update!(
-
coupon_code_id: coupon_code.id, total: discount_price, applied_discount: discount
-
)
-
OpenStruct.new(
-
success?: true,
-
data: {
-
coupon: coupon_code,
-
price: cart_value,
-
discount_type: coupon_code.discount_type,
-
cart_discount: coupon_code.discount,
-
discount_price: discount,
-
after_discount_price: discount_price
-
},
-
msg: "Coupon applied successfully",
-
code: 200
-
)
-
else
-
discount_price = (discount - cart_value)&.round(2)
-
order.update(coupon_code_id: coupon_code.id, total: 0, applied_discount: discount)
-
coupon_code.update(discount:discount_price)
-
OpenStruct.new(
-
success?: false,
-
msg: "Coupon has still left discount of #{discount_price}",
-
code: 200
-
)
-
end
-
end
-
-
def respond_error(value)
-
if value == "min"
-
min_cart_error
-
else
-
max_cart_error
-
end
-
end
-
-
def min_cart_error
-
if params[:existing_cart] == true
-
remove_coupon
-
OpenStruct.new(
-
success?: false,
-
data: nil,
-
msg: "Your coupon has been removed due to min cart limit",
-
code: 208
-
)
-
else
-
OpenStruct.new(
-
success?: false,
-
data: nil,
-
msg: "Please add few more product(s) to apply this coupon",
-
code: 208
-
)
-
end
-
end
-
-
def max_cart_error
-
if params[:existing_cart] == true
-
remove_coupon
-
OpenStruct.new(
-
success?: false,
-
data: nil,
-
msg: "Your coupon has been removed due to max cart limit",
-
code: 208
-
)
-
else
-
OpenStruct.new(
-
success?: false,
-
data: nil,
-
msg: "Your cart amount is exceeding the limit value. Please check coupon desctiption",
-
code: 208
-
)
-
end
-
end
-
-
def remove_coupon
-
order.update!(coupon_code_id: nil, applied_discount: 0)
-
order.update!(total: order.total_price, sub_total: order.total_price)
-
end
-
end
-
end
-
# rubocop:enable Metrics/MethodLength, Metrics/AbcSize
-
module BxBlockPosts
-
class Create
-
def initialize(current_user, post_attributes)
-
@current_user = current_user
-
@post_attributes = post_attributes
-
end
-
-
def execute
-
post = @current_user.posts.new(@post_attributes)
-
post.save
-
post
-
end
-
end
-
end
-
module BxBlockPosts
-
class Update
-
def initialize(post, post_attributes)
-
@post = post
-
@post_attributes = post_attributes
-
end
-
-
def execute
-
@post.assign_attributes(@post_attributes)
-
@post.save
-
@post
-
end
-
end
-
end
-
module BxBlockProfile
-
class ChangeEmailValidator
-
include ActiveModel::Validations
-
-
attr_accessor(*[
-
:account,
-
:new_email,
-
])
-
-
validates :account, :presence => {:message => 'not found'}
-
validate :validate_account_type
-
validate :validate_email
-
-
def initialize(account_id, email)
-
@account_id = account_id
-
@email = email
-
end
-
-
def account
-
return @account if defined?(@account)
-
@account = AccountBlock::Account.find_by(:id => @account_id)
-
end
-
-
private
-
-
def validate_email
-
return if AccountBlock::EmailValidation.new(@email).valid?
-
errors.add :new_email, 'is not valid'
-
end
-
-
def validate_account_type
-
return unless account
-
return unless (invalid_account_types).include?(account.type)
-
errors.add :authentication, 'field cannot be edited'
-
end
-
-
def invalid_account_types
-
['AccountBlock::EmailAccount', 'EmailAccount']
-
end
-
end
-
end
-
module BxBlockProfile
-
class ChangePasswordValidator
-
include ActiveModel::Validations
-
-
attr_accessor(*[
-
:account,
-
:new_password,
-
])
-
-
validates :account, :presence => {:message => 'not found'}
-
validate :authenticated
-
validates :new_password, :format => {
-
:with => AccountBlock::PasswordValidation.regex,
-
:multiline => true,
-
}
-
-
def initialize(account_id, password, new_password)
-
@account_id = account_id
-
@password = password
-
@new_password = new_password
-
end
-
-
def account
-
return @account if defined?(@account)
-
@account = AccountBlock::Account.find_by(:id => @account_id)
-
end
-
-
private
-
-
def authenticated
-
return unless account
-
return if account.authenticate(@password)
-
errors.add :base, 'Invalid credentials'
-
end
-
end
-
end
-
module BxBlockProfile
-
class ChangePhoneValidator
-
include ActiveModel::Validations
-
-
attr_accessor(*[
-
:account,
-
:new_phone,
-
])
-
-
validates :account, :presence => {:message => 'not found'}
-
validate :validate_account_type
-
validate :validate_phone
-
-
def initialize(account_id, phone)
-
@account_id = account_id
-
@phone = phone
-
end
-
-
def account
-
return @account if defined?(@account)
-
@account = AccountBlock::Account.find_by(:id => @account_id)
-
end
-
-
private
-
-
def validate_phone
-
return if AccountBlock::PhoneValidation.new(@phone).valid?
-
errors.add :new_phone_number, 'is not valid'
-
end
-
-
def validate_account_type
-
return unless account
-
return unless invalid_account_types.include?(account.type)
-
errors.add :authentication, 'field cannot be edited'
-
end
-
-
def invalid_account_types
-
['AccountBlock::SmsAccount', 'SmsAccount']
-
end
-
end
-
end
-
1
module BxBlockProfile
-
1
class UpdateAccountValidator
-
1
include ActiveModel::Validations
-
-
ATTRIBUTES = [
-
1
[:first_name],
-
[:last_name],
-
[:full_name],
-
[:gender],
-
[:user_name],
-
[:date_of_birth],
-
[:new_phone_number, :full_phone_number],
-
[:new_password, :password],
-
[:new_email, :email],
-
]
-
-
1
attr_accessor(*ATTRIBUTES.map(&:first))
-
1
attr_accessor :current_password
-
-
1
validates :account, :presence => {:message => 'not found'}
-
1
validates :first_name, :presence => {:allow_nil => true}
-
1
validates :last_name, :presence => {:allow_nil => true}
-
1
validates :full_name, :presence => {:allow_nil => true}
-
1
validate :validate_phone_number
-
1
validate :validate_email
-
1
validate :validate_password
-
-
1
def initialize(account_id, params)
-
@account_id = account_id
-
-
@current_password = params[:current_password]
-
-
params.keys.each do |key|
-
self.send "#{key}=", params[key]
-
end
-
end
-
-
1
def account
-
return @account if defined?(@account)
-
@account = AccountBlock::Account.find_by(:id => @account_id)
-
end
-
-
1
def attributes
-
return {} unless valid?
-
-
attrs = {}
-
-
ATTRIBUTES.each do |values|
-
source = values.first
-
dest = values.last
-
-
value = send(source)
-
attrs[dest] = value if value
-
end
-
-
attrs
-
end
-
-
1
private
-
-
1
def validate_phone_number
-
return unless new_phone_number
-
validator = ChangePhoneValidator.new(@account_id, new_phone_number)
-
validate_with_validator validator
-
end
-
-
1
def validate_password
-
return if !current_password && !new_password
-
-
validator = ChangePasswordValidator
-
.new(@account_id, current_password, new_password)
-
validate_with_validator validator
-
end
-
-
1
def validate_email
-
return unless new_email
-
validator = ChangeEmailValidator.new(@account_id, new_email)
-
validate_with_validator validator
-
end
-
-
1
def validate_with_validator(validator)
-
return if validator.valid?
-
-
validator.errors.each do |attr, message|
-
errors.add attr, message
-
end
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
# rubocop:disable Metrics/BlockLength, Lint/ConstantDefinitionInBlock
-
# patch account block
-
1
module BxBlockProfileBio
-
# patch account block validator
-
1
module PatchUpdateAccountValidator
-
1
extend ActiveSupport::Concern
-
1
included do
-
ATTRIBUTES = [
-
1
[:first_name],
-
[:last_name],
-
%i[new_phone_number full_phone_number],
-
%i[new_password password],
-
%i[new_email email], [:activated], [:gender], [:age], [:date_of_birth], [:category_ids]
-
].freeze
-
-
1
attr_accessor(*ATTRIBUTES.map(&:first))
-
-
1
def initialize(account_id, params, image_data = {})
-
@account_id = account_id
-
@current_password = params[:current_password]
-
@image_data = image_data
-
if @image_data.present?
-
@image_content_type = @image_data['content_type']
-
attach_image
-
end
-
params.each_key do |key|
-
send "#{key}=", params[key]
-
end
-
end
-
-
1
private
-
-
1
def attach_image
-
decoded_data = Base64.decode64(@image_data['data'].split(',')[1])
-
account.images.attach(
-
io: StringIO.new(decoded_data),
-
content_type: @image_data['content_type'],
-
filename: @image_data['filename']
-
)
-
end
-
-
1
def image_validation
-
return unless account.images.attached? && @image_data.present?
-
-
if %w[image/jpeg image/jpg image/png].exclude?(@image_content_type)
-
account.images.last.purge
-
errors.add(:The_profile, 'photo cannot be updated, the image is of unsupported type.')
-
return
-
end
-
set_default_image
-
end
-
-
1
def set_default_image
-
new_img = account.images.last
-
new_img.update(default_image: true)
-
ActiveStorage::Attachment.where(
-
record_type: 'AccountBlock::Account', record_id: account.id
-
).where('id != ?', new_img.id).update(default_image: false)
-
end
-
end
-
end
-
end
-
# rubocop:enable Metrics/BlockLength, Lint/ConstantDefinitionInBlock
-
module BxBlockPushNotifications
-
class Provider
-
ONE_SIGNAL = :one_signal.freeze
-
-
SUPPORTED = [ONE_SIGNAL].freeze
-
-
class << self
-
def send_push_notification(title:, message:, user_ids:, app_url:)
-
provider_klass = case provider_name
-
when ONE_SIGNAL
-
Providers::OneSignal
-
else
-
raise unsupported_message(provider_name)
-
end
-
-
provider_klass.send_push_notification(
-
title: title, message: message, user_ids: user_ids, app_url: app_url
-
)
-
end
-
-
def provider_name
-
Rails.configuration.x.push_notifications.provider
-
end
-
-
def unsupported_message(provider)
-
supported_prov_msg = "Supported: #{SUPPORTED.join(", ")}."
-
if provider
-
"Unsupported Push Notifications provider: #{provider}. #{supported_prov_msg}"
-
else
-
"You must specify a Push Notifications provider. #{supported_prov_msg}"
-
end
-
end
-
end
-
end
-
end
-
require 'net/http'
-
-
module BxBlockPushNotifications
-
module Providers
-
class OneSignal
-
API_URL = "https://onesignal.com/api/v1/notifications"
-
-
class << self
-
def send_push_notification(title:, message:, user_ids:, app_url:)
-
uri = URI.parse(API_URL)
-
-
http = Net::HTTP.new(uri.host, uri.port)
-
-
http.use_ssl = true
-
request = Net::HTTP::Post.new(
-
uri.path,
-
'Content-Type' => 'application/json;charset=utf-8',
-
'Authorization' => "Basic #{auth_token}"
-
)
-
request.body = body(
-
title: title, message: message, user_ids: user_ids, app_url: app_url
-
).to_json
-
response = http.request(request)
-
JSON.parse(response.read_body)
-
end
-
-
private
-
-
def body(title:, message:, user_ids:, app_url:)
-
{
-
'app_id' => application_id,
-
'contents' => {'en' => message},
-
'headings' => {'en' => title },
-
'app_url' => app_url,
-
'include_player_ids' => user_ids
-
}
-
end
-
-
def application_id
-
Rails.configuration.x.push_notifications.application_id
-
end
-
-
def auth_token
-
Rails.configuration.x.push_notifications.auth_token
-
end
-
end
-
end
-
end
-
end
-
module BxBlockPushNotifications
-
class SendPushNotification
-
attr_reader :title, :message, :user_ids, :app_url
-
-
def initialize(title:, message:, user_ids:, app_url: nil)
-
@title = title
-
@message = message
-
@user_ids = user_ids
-
@app_url = app_url
-
end
-
-
def call
-
Provider.send_push_notification(
-
title: title, message: message, user_ids: user_ids, app_url: app_url
-
)
-
end
-
end
-
end
-
module BxBlockSms
-
class Provider
-
TWILIO = :twilio.freeze
-
KARIX = :karix.freeze
-
TEST = :test.freeze
-
-
SUPPORTED = [TWILIO, KARIX, TEST].freeze
-
-
class << self
-
def send_sms(to, text_content)
-
provider_klass = case provider_name
-
when TWILIO
-
Providers::Twilio
-
when KARIX
-
Providers::Karix
-
when TEST
-
Providers::Test
-
else
-
raise unsupported_message(provider_name)
-
end
-
-
provider_klass.send_sms(to, text_content)
-
end
-
-
def provider_name
-
Rails.configuration.x.sms.provider
-
end
-
-
def unsupported_message(provider)
-
supported_prov_msg = "Supported: #{SUPPORTED.join(", ")}."
-
if provider
-
"Unsupported SMS provider: #{provider}. #{supported_prov_msg}"
-
else
-
"You must specify a SMS provider. #{supported_prov_msg}"
-
end
-
end
-
end
-
end
-
end
-
require "uri"
-
require "net/http"
-
-
module BxBlockSms
-
module Providers
-
class Karix
-
class << self
-
def send_sms(full_phone_number, text_content)
-
send_karix_api(full_phone_number, text_content)
-
end
-
-
private
-
-
def send_karix_api(full_phone_number, text_content)
-
url = URI(karix_message_url)
-
https = Net::HTTP.new(url.host, url.port);
-
https.use_ssl = true
-
request = Net::HTTP::Post.new(url)
-
request["Authorization"] = authorization
-
request_data = get_request_data(full_phone_number, text_content)
-
request["Content-Type"] = "application/json"
-
request.body = request_data.to_json
-
response = https.request(request)
-
puts response.read_body
-
end
-
-
def authorization
-
ActionController::HttpAuthentication::Basic.encode_credentials(
-
Rails.configuration.x.sms.account_id,
-
Rails.configuration.x.sms.auth_token
-
)
-
end
-
-
def get_request_data(full_phone_number, text_content)
-
{
-
"channel" => "sms",
-
"source" => karix_source,
-
"destination" => [full_phone_number],
-
"content" => {
-
"text" => text_content,
-
}
-
}
-
end
-
-
def karix_message_url
-
'https://api.karix.io/message/'
-
end
-
-
def karix_source
-
Rails.configuration.x.sms.from
-
end
-
end
-
end
-
end
-
end
-
module BxBlockSms
-
module Providers
-
class Test
-
class << self
-
def messages
-
@messages ||= []
-
end
-
-
def clear_messages
-
@messages = []
-
end
-
-
def send_sms(full_phone_number, text_content)
-
messages << {
-
from: Rails.configuration.x.sms.from,
-
to: full_phone_number,
-
content: text_content
-
}
-
end
-
end
-
end
-
end
-
end
-
module BxBlockSms
-
module Providers
-
class Twilio
-
class << self
-
def send_sms(full_phone_number, text_content)
-
client = ::Twilio::REST::Client.new(account_id, auth_token)
-
client.messages.create({
-
from: from,
-
to: full_phone_number,
-
body: text_content
-
})
-
end
-
-
def account_id
-
Rails.configuration.x.sms.account_id
-
end
-
-
def auth_token
-
Rails.configuration.x.sms.auth_token
-
end
-
-
def from
-
Rails.configuration.x.sms.from
-
end
-
end
-
end
-
end
-
end
-
module BxBlockSms
-
class SendSms
-
attr_reader :to, :text_content
-
-
def initialize(to, text_content)
-
@to = to
-
@text_content = text_content
-
end
-
-
def call
-
Provider.send_sms(to, text_content)
-
end
-
end
-
end
-
module BxBlockStripeIntegration
-
class AttachPaymentMethod
-
def initialize(customer_stripe_id, payment_method_id)
-
@customer_stripe_id = customer_stripe_id
-
@payment_method_id = payment_method_id
-
end
-
-
def call
-
[true, Stripe::PaymentMethod.attach(
-
@payment_method_id,
-
{customer: @customer_stripe_id}
-
)]
-
rescue Stripe::StripeError => e
-
[false, e.message]
-
end
-
end
-
end
-
module BxBlockStripeIntegration
-
class CreatePaymentMethod
-
def initialize(card_details)
-
@card_details = card_details
-
end
-
-
def call
-
if @card_details[:cvc].nil? || @card_details[:cvc].to_s.length != 3
-
return [false, "cvc is invalid"]
-
end
-
-
[true, Stripe::PaymentMethod.create(
-
{type: "card", card: @card_details.symbolize_keys}
-
)]
-
rescue Stripe::StripeError => e
-
[false, e.message]
-
end
-
end
-
end
-
#*****************************************************************
-
# * COMPANY - AVENUES INDIA PVT Ltd.,
-
#*****************************************************************
-
-
#Name of the Program : AES Encryption/Decryption
-
#Created by : AVENUES INDIA PVT Ltd., TC-Team
-
#Created On : 16-02-2014
-
#Version : Version 1.0
-
#Contribution : eLitmus Evaluation Pvt Ltd
-
#*****************************************************************
-
-
module CcAvenue
-
class Ccavenue# < ActiveRecord::Base
-
-
INIT_VECTOR = (0..15).to_a.pack("C*")
-
-
def encrypt(plain_text, key)
-
secret_key = [Digest::MD5.hexdigest(key)].pack("H*")
-
cipher = OpenSSL::Cipher::Cipher.new('aes-128-cbc')
-
cipher.encrypt
-
cipher.key = secret_key
-
cipher.iv = INIT_VECTOR
-
encrypted_text = cipher.update(plain_text) + cipher.final
-
return (encrypted_text.unpack("H*")).first
-
end
-
-
def decrypt(cipher_text,key)
-
secret_key = [Digest::MD5.hexdigest(key)].pack("H*")
-
encrypted_text = [cipher_text].pack("H*")
-
decipher = OpenSSL::Cipher::Cipher.new('aes-128-cbc')
-
decipher.decrypt
-
decipher.key = secret_key
-
decipher.iv = INIT_VECTOR
-
decrypted_text = (decipher.update(encrypted_text) + decipher.final).gsub(/\0+$/, '') rescue nil
-
return decrypted_text
-
end
-
end
-
end
-
-
require 'uri'
-
require 'net/http'
-
require 'openssl'
-
-
-
# CcAvenue::Ccavenue_Api.new.orderStatusTracker(post_data=nil)
-
module CcAvenue
-
class Ccavenueapi
-
# Provide working key share by CCAvenues
-
attr_accessor :working_key
-
-
# Provide access code Shared by CCAVENUES
-
attr_accessor :access_code
-
-
# Version Number
-
attr_accessor :version
-
-
def initialize(working_key=BxBlockGlobalSetting::GlobalSetting.last.ccavenue_api_working_key, access_code=BxBlockGlobalSetting::GlobalSetting.last.ccavenue_api_access_code, version='1.2')
-
@working_key = working_key
-
@access_code = access_code
-
@version = version
-
@url = URI(BxBlockGlobalSetting::GlobalSetting.last.api_url)
-
# @url = URI("https://apitest.ccavenue.com/apis/servlet/DoWebTrans")
-
end
-
-
def api_call(final_data)
-
http = Net::HTTP.new(@url.host, @url.port)
-
http.use_ssl = true
-
http.verify_mode = OpenSSL::SSL::VERIFY_NONE
-
-
request = Net::HTTP::Post.new(@url)
-
request.content_type = 'application/x-www-form-urlencoded'
-
request.body = final_data
-
response = http.request(request)
-
@json_data = {}
-
response.read_body.split("&").each do |str|
-
str_array = str.split("=")
-
@json_data[str_array[0]] = str_array[1]
-
end
-
if (@json_data["status"] == "0") || (@json_data["status"] == 0)
-
descrpt_response = CcAvenue::Ccavenue.new.decrypt(@json_data["enc_response"].strip, BxBlockGlobalSetting::GlobalSetting.last.ccavenue_api_working_key)
-
else
-
descrpt_response = @json_data
-
end
-
return descrpt_response
-
# information = response.body.split('&')
-
# dataSize = information.length
-
# status1 = information[0].split('=') rescue nil
-
# status2 = information[1].split('=') rescue nil
-
# status3 = information[2].split('=') rescue nil
-
-
# if status1[1] == '1'
-
# return "#{status2[1]} Error Code: #{status3[1]}"
-
# else
-
# status = self.decrypt(status2[1], @working_key)
-
# return status
-
# end
-
end
-
-
def orderStatusTracker(post_data=nil)
-
merchant_data = post_data.to_json
-
# Encrypt merchant data with working key shared by ccavenue
-
encrypted_data = self.encrypt(merchant_data, @working_key)
-
-
# make final request string for the API call
-
command = "orderStatusTracker"
-
final_data = "request_type=JSON&access_code=#{@access_code}&command=#{command}&response_type=JSON&version=#{@version}&enc_request=#{encrypted_data}"
-
result = self.api_call(final_data)
-
-
return result
-
end
-
-
def encrypt(plain_text, key)
-
secret_key = hextobin(Digest::MD5.hexdigest(key))
-
init_vector = [0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f].pack('C*')
-
cipher = OpenSSL::Cipher::AES.new(128, :CBC)
-
cipher.encrypt
-
cipher.padding = 0
-
cipher.key = secret_key
-
cipher.iv = init_vector
-
encrypted_text = cipher.update(pkcs5_pad(plain_text, 16))
-
encrypted_text << cipher.final
-
return encrypted_text.unpack('H*')[0]
-
end
-
-
# def decrypt(encrypted_text, key)
-
# secret_key = hextobin(Digest::MD5.hexdigest(key))
-
# init_vector = [0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f].pack('C*')
-
# cipher = OpenSSL::Cipher::AES.new(128, :CBC)
-
# cipher.decrypt
-
# cipher.padding = 0
-
# cipher.key = secret_key
-
# cipher.iv = init_vector
-
# decrypted_text = cipher.update([encrypted_text].pack('H*'))
-
# decrypted_text << cipher.final
-
# return pkcs5_unpad(decrypted_text)
-
# end
-
-
# def cancel_order(post_data)
-
# merchant_data = post_data.to_json
-
-
# # Encrypt merchant data with working key shared by ccavenue
-
# encrypted_data = encrypt(merchant_data, @working_key)
-
-
# # Make final request string for the API call
-
# command = 'cancelOrder'
-
# final_data = "request_type=JSON&access_code=#{@access_code}&command=#{command}&response_type=JSON&version=#{@version}&enc_request=#{encrypted_data}"
-
# result = api_call(final_data)
-
-
# return result
-
# end
-
-
-
def hextobin(hex_string)
-
length = hex_string.length
-
bin_string = ""
-
count = 0
-
-
while count < length
-
sub_string = hex_string[count, 2]
-
packed_string = [sub_string].pack("H*")
-
-
if count == 0
-
bin_string = packed_string
-
else
-
bin_string += packed_string
-
end
-
-
count += 2
-
end
-
-
return bin_string
-
end
-
-
def pkcs5_pad(plain_text, block_size)
-
pad = block_size - (plain_text.length % block_size)
-
plain_text + pad.chr * pad
-
end
-
-
# def getPendingOrders(post_data)
-
# # function for get pending orders
-
# merchant_data = post_data.to_json
-
-
# # Encrypt merchant data with working key shared by ccavenue
-
# encrypted_data = self.encrypt(merchant_data, @working_key)
-
-
# # make final request string for the API call
-
# command = "getPendingOrders"
-
# final_data = "request_type=JSON&access_code=#{@access_code}&command=#{command}&response_type=JSON&version=#{@version}&enc_request=#{encrypted_data}"
-
# result = self.api_call(final_data)
-
-
# return result
-
# end
-
-
# def confirmOrder(post_data)
-
# # function for confimorder
-
# merchant_data = post_data.to_json
-
-
# # Encrypt merchant data with working key shared by ccavenue
-
# encrypted_data = self.encrypt(merchant_data, @working_key)
-
-
# # make final request string for the API call
-
# command = "confirmOrder"
-
# final_data = "request_type=JSON&access_code=#{@access_code}&command=#{command}&response_type=JSON&version=#{@version}&enc_request=#{encrypted_data}"
-
# result = self.api_call(final_data)
-
-
# return result
-
# end
-
-
def refund_order(post_data, params)
-
merchant_data = post_data.to_json
-
encrypted_data = encrypt(merchant_data, @working_key)
-
command = params["command"] || params[:command]
-
api_version = params["version"] || params[:version]
-
final_data = "request_type=JSON&access_code=#{@access_code}&command=#{command}&response_type=JSON&version=#{api_version}&enc_request=#{encrypted_data}"
-
result = api_call(final_data)
-
return result
-
end
-
end
-
end
-
class AudioUploader < CarrierWave::Uploader::Base
-
# Include RMagick or MiniMagick support:
-
# include CarrierWave::RMagick
-
# include CarrierWave::MiniMagick
-
-
# Choose what kind of storage to use for this uploader:
-
# storage :fog
-
-
# Override the directory where uploaded files will be stored.
-
# This is a sensible default for uploaders that are meant to be mounted:
-
def store_dir
-
"uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
-
end
-
-
# Provide a default URL as a default if there hasn't been a file uploaded:
-
# def default_url(*args)
-
# # For Rails 3.1+ asset pipeline compatibility:
-
# # ActionController::Base.helpers.asset_path("fallback/" + [version_name, "default.png"].compact.join('_'))
-
#
-
# "/images/fallback/" + [version_name, "default.png"].compact.join('_')
-
# end
-
-
# Process files as they are uploaded:
-
# process scale: [200, 300]
-
#
-
# def scale(width, height)
-
# # do something
-
# end
-
-
# Create different versions of your uploaded files:
-
# version :thumb do
-
# process resize_to_fit: [50, 50]
-
# end
-
-
# Add an allowlist of extensions which are allowed to be uploaded.
-
# For images you might use something like this:
-
def extension_allowlist
-
%w(mp3 flp wav aif mid)
-
end
-
-
# Override the filename of the uploaded files:
-
# Avoid using model.id or version_name here, see uploader/store.rb for details.
-
# def filename
-
# "something.jpg" if original_filename
-
# end
-
end
-
class ExcelFileUploader < CarrierWave::Uploader::Base
-
# Include RMagick or MiniMagick support:
-
# include CarrierWave::RMagick
-
# include CarrierWave::MiniMagick
-
-
# Choose what kind of storage to use for this uploader:
-
storage :file
-
# storage :fog
-
-
# Override the directory where uploaded files will be stored.
-
# This is a sensible default for uploaders that are meant to be mounted:
-
def store_dir
-
"uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
-
end
-
-
# Provide a default URL as a default if there hasn't been a file uploaded:
-
# def default_url(*args)
-
# # For Rails 3.1+ asset pipeline compatibility:
-
# # ActionController::Base.helpers.asset_path("fallback/" + [version_name, "default.png"].compact.join('_'))
-
#
-
# "/images/fallback/" + [version_name, "default.png"].compact.join('_')
-
# end
-
def extension_allowlist
-
%w[xlsx xls]
-
end
-
-
# Process files as they are uploaded:
-
# process scale: [200, 300]
-
#
-
# def scale(width, height)
-
# # do something
-
# end
-
-
# Create different versions of your uploaded files:
-
# version :thumb do
-
# process resize_to_fit: [50, 50]
-
# end
-
-
# Add an allowlist of extensions which are allowed to be uploaded.
-
# For images you might use something like this:
-
# def extension_allowlist
-
# %w(jpg jpeg gif png)
-
# end
-
-
# Override the filename of the uploaded files:
-
# Avoid using model.id or version_name here, see uploader/store.rb for details.
-
# def filename
-
# "something.jpg" if original_filename
-
# end
-
end
-
class ImageUploader < CarrierWave::Uploader::Base
-
# Include RMagick or MiniMagick support:
-
# include CarrierWave::RMagick
-
# include CarrierWave::MiniMagick
-
-
# Choose what kind of storage to use for this uploader:
-
-
# storage :fog
-
storage :file
-
-
# Override the directory where uploaded files will be stored.
-
# This is a sensible default for uploaders that are meant to be mounted:
-
def store_dir
-
"uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
-
end
-
-
# Provide a default URL as a default if there hasn't been a file uploaded:
-
# def default_url(*args)
-
# # For Rails 3.1+ asset pipeline compatibility:
-
# # ActionController::Base.helpers.asset_path("fallback/" + [version_name, "default.png"].compact.join('_'))
-
#
-
# "/images/fallback/" + [version_name, "default.png"].compact.join('_')
-
# end
-
-
# Process files as they are uploaded:
-
# process scale: [200, 300]
-
#
-
# def scale(width, height)
-
# # do something
-
# end
-
-
# Create different versions of your uploaded files:
-
# version :thumb do
-
# process resize_to_fit: [50, 50]
-
# end
-
-
# Add an allowlist of extensions which are allowed to be uploaded.
-
# For images you might use something like this:
-
def extension_allowlist
-
%w(jpg jpeg gif png)
-
end
-
-
# Override the filename of the uploaded files:
-
# Avoid using model.id or version_name here, see uploader/store.rb for details.
-
# def filename
-
# "something.jpg" if original_filename
-
# end
-
end
-
class PdfUploader < CarrierWave::Uploader::Base
-
# Include RMagick or MiniMagick support:
-
# include CarrierWave::RMagick
-
# include CarrierWave::MiniMagick
-
-
# Choose what kind of storage to use for this uploader:
-
# storage :fog
-
storage :file
-
-
# Override the directory where uploaded files will be stored.
-
# This is a sensible default for uploaders that are meant to be mounted:
-
def store_dir
-
"uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
-
end
-
-
# Provide a default URL as a default if there hasn't been a file uploaded:
-
# def default_url(*args)
-
# # For Rails 3.1+ asset pipeline compatibility:
-
# # ActionController::Base.helpers.asset_path("fallback/" + [version_name, "default.png"].compact.join('_'))
-
#
-
# "/images/fallback/" + [version_name, "default.png"].compact.join('_')
-
# end
-
-
# Process files as they are uploaded:
-
# process scale: [200, 300]
-
#
-
# def scale(width, height)
-
# # do something
-
# end
-
-
# Create different versions of your uploaded files:
-
# version :thumb do
-
# process resize_to_fit: [50, 50]
-
# end
-
-
# Add an allowlist of extensions which are allowed to be uploaded.
-
# For images you might use something like this:
-
def extension_allowlist
-
%w(pdf)
-
end
-
-
# Override the filename of the uploaded files:
-
# Avoid using model.id or version_name here, see uploader/store.rb for details.
-
# def filename
-
# "something.jpg" if original_filename
-
# end
-
end
-
class VideoUploader < CarrierWave::Uploader::Base
-
require 'streamio-ffmpeg'
-
# Include RMagick or MiniMagick support:
-
# include CarrierWave::RMagick
-
# include CarrierWave::MiniMagick
-
-
# Choose what kind of storage to use for this uploader:
-
# storage :fog
-
-
# Override the directory where uploaded files will be stored.
-
# This is a sensible default for uploaders that are meant to be mounted:
-
def store_dir
-
"uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
-
end
-
-
# Provide a default URL as a default if there hasn't been a file uploaded:
-
# def default_url(*args)
-
# # For Rails 3.1+ asset pipeline compatibility:
-
# # ActionController::Base.helpers.asset_path("fallback/" + [version_name, "default.png"].compact.join('_'))
-
#
-
# "/images/fallback/" + [version_name, "default.png"].compact.join('_')
-
# end
-
-
# Process files as they are uploaded:
-
# process scale: [200, 300]
-
#
-
# def scale(width, height)
-
# # do something
-
# end
-
-
# Create different versions of your uploaded files:
-
# version :thumb do
-
# process resize_to_fit: [50, 50]
-
# end
-
-
# Add an allowlist of extensions which are allowed to be uploaded.
-
# For images you might use something like this:
-
def extension_allowlist
-
%w(webm mpg mp2 mpeg mpe mpv ogg mp4 m4p m4v avi wmv mov qt flv swf avcdhd mp3)
-
end
-
-
# Override the filename of the uploaded files:
-
# Avoid using model.id or version_name here, see uploader/store.rb for details.
-
# def filename
-
# "something.jpg" if original_filename
-
# end
-
end
-
module BxBlockAppointmentManagement
-
# Create slot for 6 days in advance
-
class AddOneDayAvailabilityWorker
-
include Sidekiq::Worker
-
-
def perform availability_id
-
availability_for_id(availability_id)
-
slot_for_today = BxBlockAppointmentManagement::Availability.find_by(
-
service_provider_id: @availability.service_provider_id,
-
availability_date: Date.today.strftime("%d/%m/%Y")
-
).present?
-
unless !@availability.present? && slot_for_today
-
value = @availability.dup
-
value.availability_date = (Date.today+1).strftime("%d/%m/%Y")
-
value.save!
-
trriger_job
-
end
-
end
-
-
def trriger_job
-
BxBlockAppointmentManagement::AddOneDayAvailabilityWorker.perform_at(
-
1.days.from_now, @availability.id
-
)
-
end
-
-
def availability_for_id id
-
@availability = BxBlockAppointmentManagement::Availability.find(id)
-
end
-
end
-
end
-
module BxBlockAppointmentManagement
-
# Create slot for 6 days in advance
-
class CreateAvailabilityWorker
-
include Sidekiq::Worker
-
-
def perform availability_id
-
availability_for_id(availability_id)
-
if @availability.present?
-
build_slots
-
trriger_job
-
end
-
end
-
-
def trriger_job
-
BxBlockAppointmentManagement::AddOneDayAvailabilityWorker.perform_at(
-
7.days.from_now, @availability.id
-
)
-
end
-
-
def availability_for_id id
-
@availability = BxBlockAppointmentManagement::Availability.find(id)
-
end
-
-
def build_slots
-
date = Date.strptime(@availability.availability_date, "%d/%m/%Y") + 1.days
-
6.times do
-
value = @availability.dup
-
value.availability_date = date.strftime("%d/%m/%Y")
-
value.save
-
date += 1.days
-
end
-
end
-
end
-
end
-
module BxBlockSplitpayments
-
class SplitPaymentWorker
-
include Sidekiq::Worker
-
def perform(*args)
-
@orders = BxBlockShoppingCart::Order.where(status: "completed", payment_mode: "online", is_split: false)
-
@orders.each do |order|
-
BxBlockSplitpayments::Order.complete_order(order)
-
end
-
end
-
end
-
end